How To Create A Dialog Box In A Non-ui Thread In A Different Class?
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 i
Solution 1:
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.
publicclassMyGame {
private Context context;
private Handler handler;
publicMyClass(Context context){
this.context = context;
handler = newHandler(Looper.getMainLooper());
}
...
}
and when initializing from activity
MyGamegame=newMyGame(this);
and to show the dialog in your game class, just use this code
handler.post(new Runnable() {
publicvoidrun() {
// Instanitiate your dialog here
showMyDialog();
}
});
and this how to show a simple AlertDialog.
privatevoidshowMyDialog() {
new AlertDialog.Builder(context)
.setTitle("Som title")
.setMessage("Are you sure?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
Solution 2:
You need to go back to the UI thread to show the dialog, but you will need a reference to the current Activity (MainActivity I assume) to access to the UI thread and to use as a Context of the dialog. Check the method runOnUiThread
Post a Comment for "How To Create A Dialog Box In A Non-ui Thread In A Different Class?"