将数据从活动传递到对话框

jsw*_*jsw 9 android

我正在寻找一种方法将数据从活动传递到对话框.我试图打电话showDialog(int);,但是我没有看到将任何数据传递到对话框的方法.我需要将一个字符串传递给对话框以显示确认:)

干杯

ina*_*ruk 13

如果您的目标是Android 2.2(API级别8或更高级别),则可以使用

 public final boolean showDialog (int id, Bundle args)
Run Code Online (Sandbox Code Playgroud)

并传递你的论点Bundle.见文档.

如果要支持较旧的Android版本,则应将参数保存在Activity类成员中,然后从onPrepareDialog函数中访问它们.请注意,onCreateDialog这不符合您的需求,因为它仅为对话框创建调用一次.

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);
         }             
    }
}
Run Code Online (Sandbox Code Playgroud)