简体   繁体   English

从uiThread Runnable中显示Toast消息?

[英]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. 我想在UiThread上运行的线程中显示一个Toast消息,但是看起来我的调用中没有正确引用Runnable。 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. 我相信不是makeText函数所需的实际runnable。 How would you get the actual Runnable in this case? 在这种情况下,你如何获得实际的Runnable?

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. 不要使用this关键字,最佳做法是创建Context变量并在onCreate方法中初始化它,并使用活动中的每个位置。

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. 在您的情况下,这指的是runnable类而不是Context。 so you can use context for toast 所以你可以使用contexttoast

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 . this指的是runnable类而不是context so you can use the activityname.this 所以你可以使用activityname.this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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