How do you display a Toast from a background thread on Android?

后端 未结 11 2030
难免孤独
难免孤独 2020-11-22 05:03

How can I display Toast messages from a thread?

11条回答
  •  野性不改
    2020-11-22 05:45

    Like this or this, with a Runnable that shows the Toast. Namely,

    Activity activity = // reference to an Activity
    // or
    View view = // reference to a View
    
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            showToast(activity);
        }
    });
    // or
    view.post(new Runnable() {
        @Override
        public void run() {
            showToast(view.getContext());
        }
    });
    
    private void showToast(Context ctx) {
        Toast.makeText(ctx, "Hi!", Toast.LENGTH_SHORT).show();
    }
    

提交回复
热议问题