按下返回鍵,出現選單視窗,最簡單的寫法,就是這種。
程式結果畫面如下:
程式:
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onKeyDown(int keyCode,KeyEvent event){
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){ //確定按下退出鍵and防止重複按下退出鍵
dialog();
}
return false;
}
private void dialog(){
// setItems顯示選單視窗.
new AlertDialog.Builder(this).setTitle("請選擇一樣").setItems(new String[] { "項目A", "項目B" }, null).setNegativeButton("確定", null).show();
}
@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;
}
}
留言列表