問題描述
我正在 android 中開發(fā)一個非常簡單的游戲(在非 UI 線程中運行),我想這樣做,當(dāng)游戲結(jié)束時,它會顯示一個帶有分?jǐn)?shù)的自定義對話框,但類是不在 MainActivity 類中.我不知道如何在沒有任何錯誤的情況下在線程中創(chuàng)建對話框.
I'm developing a very simple game in android(that runs in a non-UI thread), I want to make that, when the game is over, it shows a custom dialog box with the score, but the class isn't in the MainActivity class. I can't figure out how to create the dialog in the thread whitout getting any error.
推薦答案
有很多方法可以做到這一點.一種方法是將您的 context 傳遞給游戲的類構(gòu)造函數(shù),以便能夠通過它訪問 UI.
There are so many ways to do that. One way is to pass your context to the class constructor of the game to be able to access the UI through it.
public class MyGame {
private Context context;
private Handler handler;
public MyClass(Context context) {
this.context = context;
handler = new Handler(Looper.getMainLooper());
}
...
}
以及從活動初始化時
MyGame game = new MyGame(this);
要在您的游戲類中顯示對話框,只需使用此代碼
and to show the dialog in your game class, just use this code
handler.post(new Runnable() {
public void run() {
// Instanitiate your dialog here
showMyDialog();
}
});
以及如何顯示一個簡單的 AlertDialog.
and this how to show a simple AlertDialog.
private void showMyDialog() {
new AlertDialog.Builder(context)
.setTitle("Som title")
.setMessage("Are you sure?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
這篇關(guān)于如何在不同類的非 UI 線程中創(chuàng)建對話框?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!