I created a custom dialog and I'd like to start a new activity when OK is clicked. How can I get the context to set it as first argument of my Intent constructor?
I can create the intent using getContext()
, but I can't call startActivity
. Shall I pass the activity calling the dialog to the dialog's constructor? Is it the usual way to start an activity by clicking a dialog?
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
}
}
}
To create a DialogFragment , first create a class that extends DialogFragment , and override onCreateDialog() , as shown in the following example. Similar to how onCreateView() should create a root View in an ordinary fragment, onCreateDialog() should create a Dialog to display as part of the DialogFragment .
You must call the second activity using the startActivityForResult method. In your second activity, when it is finished, you can execute the setResult method where basically you put the result information. Then, on your first activity, you override the onActivityResult method.
I suggest you use this. It makes it so simple:
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]
is my data which is shown. You can replace this with your own message.
Intent i = new Intent(getBaseContext(), ItemSelection.class);
This worked for me although the structure is different, there is no class for the dialog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With