Error due to invalid combination of Toast and OnClickListener

前端 未结 7 1956
醉梦人生
醉梦人生 2021-01-31 08:54

I\'m trying to use Toast inside OnCLickListener. My code triggers the following error:

The method makeText(Context, CharSequence, int)          


        
7条回答
  •  离开以前
    2021-01-31 09:03

    Anywhere, just use the following:

    ((Activity) mContext).runOnUiThread(new Runnable() {
                        public void run() {
                            Toast my_toast = Toast.makeText(mContext, "YOUR TEXT OR STRING", Toast.LENGTH_LONG);
                            my_toast.setGravity(Gravity.CENTER, 0, 0);
                            my_toast.show();
                        }
                    });
    

    You just need to define at the top of your activity (just after the onCreate):

    mContext = this;
    

    Also, see that I decomposed it a bit to be able to handle the gravity as I want (sometimes you may want the toast to appear at the center of the screen)...

提交回复
热议问题