“android.view.WindowManager$BadTokenException: Unable to add window” on buider.show()

前端 未结 10 785
忘掉有多难
忘掉有多难 2020-11-22 10:43

From my main activity, I need to call an inner class and in a method within the class, I need to show AlertDialog. After dismissing it, when the OK

10条回答
  •  北海茫月
    2020-11-22 11:08

    with this globals variables idea, I saved MainActivity instance in onCreate(); Android global variable

    public class ApplicationController extends Application {
    
        public static MainActivity this_MainActivity;
    }
    

    and Open dialog like this. it worked.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Global Var
        globals = (ApplicationController) this.getApplication();
        globals.this_MainActivity = this;
    }
    

    and in a thread, I open dialog like this.

    AlertDialog.Builder alert = new AlertDialog.Builder(globals.this_MainActivity);
    
    1. Open MainActivity
    2. Start a thread.
    3. Open dialog from thread -> work.
    4. Click "Back button" ( onCreate will be called and remove first MainActivity)
    5. New MainActivity will start. ( and save it's instance to globals )
    6. Open dialog from first thread --> it will open and work.

    : )

提交回复
热议问题