自定义对话框在android中传递值

时间:2011-07-30 09:59:23

标签: android dialog

如何通过自定义选择的Dialog类将值传递回活动?...我正在点击一个图像的应用程序将出现一个对话框类,我将选择一个值...我需要更新这些值后面的活动..任何人都建议我吗?

2 个答案:

答案 0 :(得分:3)

如果您正在使用扩展Dialog的类,则可以在单击对话框按钮时为要执行的操作添加接口(例如在调用活动中设置值),然后在构造函数中设置回调。像这样:

public class CustomDialog extends Dialog {

    // this is your interface for what you want to do on the calling activity
    public interface ICustomDialogEventListener {
        public void customDialogEvent(int valueYouWantToSendBackToTheActivity);
    }

    private ICustomDialogEventListener onCustomDialogEventListener;

    // In the constructor, you set the callback 
    public CustomDialog(Context context,
            ICustomDialogEventListener onCustomDialogEventListener) {
        super(context);
        this.onCustomDialogEventListener = onCustomDialogEventListener;
    }

    // And in onCreate, you set up the click event from your dialog to call the callback
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Button btnOk = (Button) findViewById(R.id.customDialogButton);
        btnOk.setOnClickListener( new Button.OnClickListener()
        {
            public void onClick(View v) {
                onCustomDialogEventListener.customDialogEvent(valueYouWantToSendBackToTheActivity);
                dismiss();
             }
         });
     }
}

当您想要使用对话框时,可以使用设置调用活动中的值的回调构建它:

final CustomDialog dialog = new CustomDialog(this, new ICustomDialogEventListener() {
        public void customDialogEvent(int value) {
            // Do something with the value here, e.g. set a variable in the calling activity
        }
    });

答案 1 :(得分:0)

如果您的对话框是主题声明为Dialog的活动,您应该检查如何在活动中使用startActivityForResult();
您可以通过它将活动2中的数据传输到活动1。

相关问题