简体   繁体   中英

Show a Toast message from inside uiThread Runnable?

I want to show a toast message from within a thread that is running on the UiThread however it appears the Runnable is not referenced correctly in my call. Please see my very basic implementation below:

this.runOnUiThread(new Runnable() {
     public void run() {
                Toast.makeText(this, "Authenticated.", Toast.LENGTH_SHORT).show();
            }
        }
);

I believe that this is not the actual runnable that the makeText function requires. How would you get the actual Runnable in this case?

do not use this keyword,best practice is to create Context variable and initialize it in onCreate method,and use every where in your activity.

Context context;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layoutname);
    context=this;
}   

now use it like this:

this.runOnUiThread(new Runnable() {
     public void run() {
                Toast.makeText(context, "Authenticated.", Toast.LENGTH_SHORT).show();
            }
        }
);

in your case,this refers to the runnable class not the Context. so you can use context for toast

use this

this.runOnUiThread(new Runnable() {
     public void run() {
                Toast.makeText(youractivityname.this, "Authenticated.", Toast.LENGTH_SHORT).show();
            }
        }
);

this refers to the runnable class not the context . so you can use the activityname.this

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