简体   繁体   中英

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
}
}
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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM