This question already has an answer here:
这个问题在这里已有答案:
- How to create a dialog box in a non-UI thread in a different class? 2 answers
如何在不同类的非UI线程中创建对话框? 2个答案
I'm making a very little game in a "GameView" with a "GameThread" inside it. It extends from View so I use this constructor:
我在“GameView”中制作了一个非常小的游戏,里面有一个“GameThread”。它从View扩展,所以我使用这个构造函数:
GameView(Context context, AttributeSet attrs){
//initialization stuff
}
and I add it on the main_activity.xml because its controlled by buttons. The problem is that I want to make that when the game is over, it shows a Dialog with the score. But I don't know how to do this. I 've tried creating a reference to the context with a class attribute like this:
我将它添加到main_activity.xml上,因为它由按钮控制。问题是我希望在游戏结束时制作它,它会显示带有分数的Dialog。但我不知道该怎么做。我尝试使用类属性创建对上下文的引用:
GameView(Context context, AttributeSet attrs){
this.context = context;
}
But i can't call "runOnUIThread" with this.
但是我不能用这个叫“runOnUIThread”。
1 个解决方案
#1
You can use a UI thread's handler instead. Get an instance using your context and post your Runnable
您可以使用UI线程的处理程序。使用您的上下文获取实例并发布您的Runnable
Handler handler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
//Do something in your UI thread
}
};
handler.post(myRunnable);
#1
You can use a UI thread's handler instead. Get an instance using your context and post your Runnable
您可以使用UI线程的处理程序。使用您的上下文获取实例并发布您的Runnable
Handler handler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
//Do something in your UI thread
}
};
handler.post(myRunnable);