How to handle screen orientation change when progress dialog and background thread active?

前端 未结 28 1818
轮回少年
轮回少年 2020-11-22 07:03

My program does some network activity in a background thread. Before starting, it pops up a progress dialog. The dialog is dismissed on the handler. This all works fine, exc

28条回答
  •  独厮守ぢ
    2020-11-22 07:48

    If you're struggling with detecting orientation change events of a dialog INDEPENDENT OF AN ACTIVITY REFERENCE, this method works excitingly well. I use this because I have my own dialog class that can be shown in multiple different Activities so I don't always know which Activity it's being shown in. With this method you don't need to change the AndroidManifest, worry about Activity references, and you don't need a custom dialog (as I have). You do need, however, a custom content view so you can detect the orientation changes using that particular view. Here's my example:

    Setup

    public class MyContentView extends View{
        public MyContentView(Context context){
            super(context);
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig){
            super.onConfigurationChanged(newConfig);
    
            //DO SOMETHING HERE!! :D
        }
    }
    

    Implementation 1 - Dialog

    Dialog dialog = new Dialog(context);
    //set up dialog
    dialog.setContentView(new MyContentView(context));
    dialog.show();
    

    Implementation 2 - AlertDialog.Builder

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    //set up dialog builder
    builder.setView(new MyContentView(context));        //Can use this method
    builder.setCustomTitle(new MycontentView(context)); // or this method
    builder.build().show();
    

    Implementation 3 - ProgressDialog / AlertDialog

    ProgressDialog progress = new ProgressDialog(context);
    //set up progress dialog
    progress.setView(new MyContentView(context));        //Can use this method
    progress.setCustomTitle(new MyContentView(context)); // or this method
    progress.show();
    

提交回复
热议问题