Android 我可以举一个使用 runOnUiThread 显示吐司的例子吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11791157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:53:56  来源:igfitidea点击:

Can i have an example of displaying a toast using runOnUiThread.

androidmultithreadingtoast

提问by Sourav301

I searched many places but could not find a complete working example of implementation of "runOnUiThread". I tried a lot , but getting lots of errors . I just want to display a toast from a thread.

我搜索了很多地方,但找不到“runOnUiThread”实现的完整工作示例。我尝试了很多,但得到了很多错误。我只想显示一个线程的祝酒词。

回答by Sourav301

So here is the final full code. Thanks to all who have replied.

所以这是最终的完整代码。感谢所有回复的人。

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MainActivity.this.runOnUiThread(new Runnable() {

        public void run() {
            Toast.makeText(MainActivity.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();

        }
    });
}

}

And About the XML, its is the default XML file created. No change needed.

关于 XML,它是创建的默认 XML 文件。不需要改变。

回答by Samir Mangroliya

YourActivityName.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(YourActivityName.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();

            }
        });

回答by deepGrave

To answer Nefariisquestion, I had the same problem, and needed to toast from a non-activity class, to solve it you can pass Context to the function your calling runOnUiThreadfrom.

为了回答Nefariis 的问题,我遇到了同样的问题,需要从非活动类中敬酒,要解决它,您可以将 Context 传递给您runOnUiThread从中调用的函数。

For example:

例如:

public class FlashCardsUtil
{
    public static void fillTableFromFile(SQLiteDatabase pSqLiteDatabase, final Context pContext, String pFileName)
    {
        ...

        runOnUiThread(new Runnable()
        {
            public void run()
            {
                Toast.makeText(pContext, "Success filling database", Toast.LENGTH_SHORT).show();
            }
        });
    }
}