TQC-105 設定 menu、AlertDialog

TQC-105 設定 menu、AlertDialog

這是TQC的105題,

程式碼為自行撰寫,

僅供參考。

 

最主要練習設定menu、AlertDialog

 

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.add(0, MENU_ADD, 0, "ADD");
    	menu.add(0, MENU_DEL, 0, "DEL");
    	menu.add(0, MENU_ABOUT, 0, "關於");
    	menu.add(0, MENU_Quit, 0, "結束");
    	//新增menu選單,再利用onOptionsItemSelected擷取選單選擇項目,處理相對應的事件
    	
    	return true ;	
    }
    //menu被選擇執行後的事件處理
    public boolean onOptionsItemSelected(MenuItem item){
    	//點選menu,出現四個選擇,以switch區分點選何項,設定title並繫結至其功能
    	switch(item.getItemId()){
    	case MENU_ABOUT:
    		openAboutDialog();
    		break;
    	case MENU_Quit:
    		openExitDialog();
    		break;
    	}
    	return super.onOptionsItemSelected(item) ;
    }
    
    //點選「關於」功能
    public void openAboutDialog()
    {    	
    	AlertDialog.Builder dialog=new AlertDialog.Builder(this);
    	dialog.setTitle("ABOUT");
    	dialog.setMessage("TQC");
    	dialog.setPositiveButton("確認",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
    	 dialog.show();
    }
    //點選「離開」功能
    public void openExitDialog()
    {
       	//開啟視窗詢問【是否確認離開系統?】,於訊息視窗點選「確認」後,關閉程式
    	//於訊息視窗點選「取消」,則關閉此詢問視窗,則回到MENU功能選單畫面
    	
    	AlertDialog.Builder dialog=new AlertDialog.Builder(this);
    	dialog.setTitle("ABOUT");
    	dialog.setMessage("TQC");
    	dialog.setPositiveButton("確認",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				finish();
			}
		});
    	
    	dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
    	 dialog.show();
    
    }
}

 

 

自我LV~