[英]How to show alert dialogue from another thread?
I've got an app that has a class that's linked to a layout. 我有一个具有链接到布局的类的应用程序。 This layout then runs a process in another thread to avoid freezing the layout.
然后,此布局在另一个线程中运行一个进程,以避免冻结布局。 Eventually, the code in the second thread is supposed to show a dialogue on the layout in the first thread.
最终,第二个线程中的代码应该显示第一个线程中的布局对话框。 The code is running.
代码正在运行。 I know this because I put a print statement at the end of it, but the dialogue isn't showing up.
我知道这一点是因为我在其末尾添加了打印声明,但没有显示对话。
So how do I make the dialogue show up once the thread is done? 那么,一旦线程完成,如何使对话框显示出来? As far as I can tell, I can't just plop it into another thread, so i'm stumped.
据我所知,我不能只是将其放入另一个线程中,所以我很困惑。 Any help would be appreciated.
任何帮助,将不胜感激。
Create object of Handler in onCreate() 在onCreate()中创建Handler对象
mHandler=new Handler();
then 然后
write following code inside your thread where you want to display dialog or to update any UI views. 在您要显示对话框或更新任何UI视图的线程内编写以下代码。
mHandler.post(new Runnable() {
public void run(){
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
//Add all dialog prepaation code
}
});
For more information refer Background processing in Android 有关更多信息,请参阅Android中的后台处理。
You need to use runOnUiThread from the thread to access your views and update/edit it. 您需要使用线程中的runOnUiThread来访问您的视图并对其进行更新/编辑。
runOnUiThread(new Runnable() {
@Override
public void run() {
btn.setText("#");
//show your dialog here
//do your work here
}
});
and if you are using fragments just add getActivity()
before runOnUiThread
如果您使用的是片段,只需在
runOnUiThread
之前添加getActivity()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.