Android: How to get a modal dialog or similar modal behavior?

后端 未结 11 1916
暗喜
暗喜 2020-12-01 05:17

These days I\'m working on simulating modal dialog in Android. I\'ve googled a lot, there\'s much discussions but sadly there\'s not much options to get it modal. Here\'s so

11条回答
  •  情歌与酒
    2020-12-01 05:36

    It is not possible the way you planned. First, you are not allowed to block the UI thread. Your application will be terminated. Second, need to handle the lifecycle methods that are called when another activity is started with startActivity (your original acitvity will be paused while the other activity is running). Third, you probably could somehow hack it by using startAlertDialog() not from the UI thread, with thread synchronization (like Object.wait()) and some AlertDialog. However, I strongly encourage you to not do this. It is ugly, will certainly break and it's just not the way things are intended to work.

    Redesign your approach to capture the asynchronous nature of these events. If you want for example some dialog which asks the user for a decsision (like accepting the ToS or not) and do special actions based on that decision create a dialog like this:

    AlertDialog dialog = new AlertDialog.Builder(context).setMessage(R.string.someText)
                    .setPositiveButton(android.R.string.ok, new OnClickListener() {
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            // Do stuff if user accepts
                        }
                    }).setNegativeButton(android.R.string.cancel, new OnClickListener() {
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            // Do stuff when user neglects.
                        }
                    }).setOnCancelListener(new OnCancelListener() {
    
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            dialog.dismiss();
                            // Do stuff when cancelled
                        }
                    }).create();
    dialog.show();
    

    Then have two methods handling positive or negative feedback accordingly (i.e. proceeding with some operation or finishing the activity or whatever makes sense).

提交回复
热议问题