如何从Android中的对话框启动活动

jul*_*jul 9 android dialog android-context

我创建了一个自定义对话框,我想在单击"确定"时启动一个新活动.如何将上下文设置为我的Intent构造函数的第一个参数?

我可以使用创建意图getContext(),但我不能打电话startActivity.我应该将调用对话框的活动传递给对话框的构造函数吗?这是通过单击对话框启动活动的常用方法吗?

public class CustomDialog extends Dialog implements OnClickListener {
    Button okButton, cancelButton;

    public CustomDialog(Context context) {      
        super(context);     
        setContentView(R.layout.custom_dialog);
        okButton = (Button) findViewById(R.id.button_ok);
        okButton.setOnClickListener(this);
        cancelButton = (Button) findViewById(R.id.button_cancel);
        cancelButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {       
        if (v == cancelButton)
            dismiss();
        else {
            Intent i = new Intent(getContext(), ItemSelection.class);
            startActivity(i); //The method startActivity(Intent) is undefined for the type CustomDialog
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rch 19

public class CustomDialog extends Dialog implements OnClickListener {
  Button okButton, cancelButton;
  Activity mActivity;

  public CustomDialog(Activity activity) {      
    super(activity);
    mActivity = activity;
    setContentView(R.layout.custom_dialog);
    okButton = (Button) findViewById(R.id.button_ok);
    okButton.setOnClickListener(this);
    cancelButton = (Button) findViewById(R.id.button_cancel);
    cancelButton.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {       
    if (v == cancelButton)
        dismiss();
    else {
        Intent i = new Intent(mActivity, ItemSelection.class);
        mActivity.startActivity(i);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


lor*_*ess 5

Intent i = new Intent(getBaseContext(), ItemSelection.class);
Run Code Online (Sandbox Code Playgroud)

尽管结构不同,但这对我有用,但对话框没有类。