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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top