(1)利用menu按鈕,改變setTitle
package COM.TQC.GDD01; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class GDD01 extends Activity { // ... /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } protected static final int MENU_ADD=Menu.FIRST; protected static final int MENU_DEL=Menu.FIRST+1; protected static final int MENU_ABOUT=Menu.FIRST+2; protected static final int MENU_Quit=Menu.FIRST+3; @Override //建立menu選單的項目 public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); //新增menu選單,再利用onOptionsItemSelected擷取選單選擇項目,處理相對應的事件 menu.add(0,MENU_ADD,0,getString(R.string.menu_add)); menu.add(0,MENU_DEL,0,getString(R.string.menu_delete)); menu.add(0,MENU_ABOUT,0,getString(R.string.menu_about)); menu.add(0,MENU_Quit,0,getString(R.string.menu_exit)); return true ; } //menu被選擇執行後的事件處理 public boolean onOptionsItemSelected(MenuItem item){ //點選menu,出現四個選擇,以switch區分點選何項,設定title並繫結至其功能 switch(item.getItemId()){ case MENU_ADD: setTitleAdd(); break; case MENU_DEL: setTitleDEL(); break; case MENU_ABOUT: openAboutDialog(); break; case MENU_Quit: openExitDialog(); break; } return super.onOptionsItemSelected(item) ; } private void setTitleAdd() { // TODO Auto-generated method stub setTitle(getString(R.string.menu_add)); } private void setTitleDEL() { // TODO Auto-generated method stub setTitle(getString(R.string.menu_delete)); } //點選「關於」功能 public void openAboutDialog() { setTitle(getString(R.string.menu_about)); AlertDialog.Builder dialog=new AlertDialog.Builder(this); dialog.setTitle(R.string.menu_add); //新增項目 dialog.setMessage(R.string.menu_about_msg); //TQC+ Android認證題庫 dialog.setPositiveButton(R.string.str_ok,new DialogInterface.OnClickListener() { //確認 @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub } }); dialog.show(); } //點選「離開」功能 public void openExitDialog() { //開啟視窗詢問【是否確認離開系統?】,於訊息視窗點選「確認」後,關閉程式 //於訊息視窗點選「取消」,則關閉此詢問視窗,則回到MENU功能選單畫面 AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(R.string.menu_exit);//離開 dialog.setMessage(R.string.menu_exit_msg); //是否確認離開系統 dialog.setPositiveButton(R.string.str_ok,new DialogInterface.OnClickListener(){ //確認 @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub finish(); } }); dialog.setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() { //取消 @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub //dialog.dismiss(); } }); dialog.show(); } }