0
我已經創建了一個菜單並在其上放置了退出按鈕。現在當我點擊它時,它就像後退按鈕並關閉活動。菜單項顯示正確,但是當我選擇,然後沒有發生。請告訴我解決這個問題。退出菜單無法正常工作
這裏的菜單/ main.xml中
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/exit_menu"
android:title="Exit"
android:showAsAction="ifRoom" />
</menu>
這裏的MainActivity.java
package com.testing.exitMenu;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.view.*;
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.exit_menu:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(exit);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}