Anat's
Anat's

Reputation: 411

How to make custom toast in OnReceive(under Broadcast) class?

I'M making application in android studio and we try to show up custom toast regularly. But since Broadcast don't have "View" , I can't use codes below.

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.toast_bad0, (ViewGroup) view.findViewById(R.id.toast_layout_bad0));

Toast toast = new Toast(mcontext.getApplicationContext());

                    toast.setGravity(Gravity.CENTER,0,0);
                    toast.setDuration(Toast.LENGTH_SHORT);
                    toast.setView(layout);
                    toast.show();

//toast_layout_bad0 is the name of xml file we designed for toast.

I'm thinking of using interface but I'm not sure. Is there some way that I can use custom toast in Broadcast?

public class Broadcast extends BroadcastReceiver {
    final String strId =  "my_channel_01";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("abc","Toast");
        Toast.makeText(context,"sdf",Toast.LENGTH_LONG).show();//We want to change this simple toast to custom toast
}
}

Upvotes: 0

Views: 276

Answers (1)

user13847329
user13847329

Reputation: 11

LayoutInflater inflater = getLayoutInflater();

Alter the above line of text to the following:

LayoutInflater inflater=LayoutInflater.from(context);
View layout = inflater.inflate(R.layout.toast_bad0, 
              (ViewGroup) view.findViewById(R.id.toast_layout_bad0));

Alter the above line of text to the following:

View layout = inflater.inflate(R.layout.toast_bad0, null);
Toast toast = new Toast(context);

toast.setGravity(Gravity.CENTER,0,0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();

Upvotes: 1

Related Questions