public void Home (View view){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Back");
dialog.setIcon(R.drawable.logo);
dialog.setCancelable(true);
dialog.setMessage("Do you want to go back?");
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
});
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
Now I stay at pageOne.java when I click button "Home". I want to go back to MainActivity.java but I get an error.
Your usage of this
is a problem:
new Intent(this, MainActivity.class);
In that scope, it thinks this
is referring to the anonymous inner class DialogInterface.OnClickListener
. So instead, you should use a reference to your outer class instance like HomeActivity.this
(or whatever your activity is called).
new Intent(HomeActivity.this, MainActivity.class);
"this" you used in ClickListener refer to the Click Event Listener.
But need to add is YourActivity.this, and if it is a fragment call getActivity() instead of "this".
I hope it will be OK for you.
public void Home (View view){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Back");
dialog.setIcon(R.drawable.logo);
dialog.setCancelable(true);
dialog.setMessage("Do you want to go back?");
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(pageOne.this, MainActivity.class);
startActivity(intent);
}
});
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
您可以尝试Intent intent = new Intent(pageOne.this, MainActivity.class);
Use getApplicationContext or Activity.this. It is good to use this method.
Intent in=new Intent(PageOne.this,MainActivity. this);
startActivity(in);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.