Pass Data From Activity To Dialog

后端 未结 4 1266
一整个雨季
一整个雨季 2021-01-17 21:31

I am looking for a way to pass data from an activity onto a dialog box. I am trying to call showDialog(int);, however i don\'t see a way to pass any data to the

4条回答
  •  醉酒成梦
    2021-01-17 21:57

    If you are targeting Android 2.2 (API Level 8 or higher) you can use

     public final boolean showDialog (int id, Bundle args)
    

    And pass your arguments in Bundle. See documentation.

    If you want to support older Android versions, you should save your arguments in Activity class members and then access them from your onPrepareDialog function. Note that onCreateDialog won't fit your needs as it's called only once for dialog creation.

    class MyActivity {
    
        private static int MY_DLG = 1;
        private String m_dlgMsg;
    
        private showMyDialog(String msg){
            m_dlgMsg = msg;
            showDialog(MY_DLG);
        }
    
        private doSomething() {
            ...
            showMyDlg("some text");
        }
    
        protected void onCreateDialog(int id){
            if(id == MY_DLG){
                AlertDialog.Builder builder = new AlertDialog.Builder(this); 
                ....
                return builder.create();
             }
             return super.onCreateDialog(id);
        }        
    
        @Override
        protected void onPrepareDialog (int id, Dialog dialog){ 
             if(id == MY_DLG){ 
                AlertDialog adlg = (AlertDialog)dialog;
                adlg.setMessage(m_dlgMsg);
             } else {
                super.onPrepareDialog(id, dialog);
             }             
        }
    }
    

提交回复
热议问题