我创建了一个自定义对话框,我想在单击“确定”时启动一个新活动。如何将上下文设置为我的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
}
}
}
答案 0 :(得分:18)
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);
}
}
}
答案 1 :(得分:4)
Intent i = new Intent(getBaseContext(), ItemSelection.class);
这对我有用,虽然结构不同,但对话框没有课程。
答案 2 :(得分:3)
答案 3 :(得分:2)
简单,只需保存传递到局部变量中的CustomDialog构造函数的上下文。
答案 4 :(得分:1)
与Cheezmeister wrote一样,没有必要获取活动。你可以简单地使用这样的上下文:
Intent i = new Intent(getContext(), ItemSelection.class);
getContext().startActivity(i);
答案 5 :(得分:0)
我建议你用这个。它变得如此简单:
AlertDialog.Builder dialog = new AlertDialog.Builder(RegistrationActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Error Alert");
dialog.setMessage(info[1]);
dialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity.class);
startActivity(intent);
}
})
.setNegativeButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog alert = dialog.create();
alert.show();
info[1]
是显示的数据。您可以将此替换为您自己的消息。
答案 6 :(得分:0)
如果你正在使用DialogFragment,你可以这样做:
public class MyDialogFragment : DialogFragment
{
private Context _Context;
...
public override void OnActivityCreated(Bundle savedInstanceState)
{
_Context = Context;
...
alertDialog.SetButton("Start Activity Button", delegate
{
var uri = Android.Net.Uri.Parse("https://.....");
var intent = new Intent(Intent.ActionView, uri);
_Context.StartActivity(intent);