今天就來介紹Menu(菜單),可以幫助應用程式做一些共用功能如:設定、重新整理
結束、關於我、說明.....等,可以說也是一個蠻實用及常用的功能之一
下面就開始為您說明如果在應用程式中加入Menu功能:
因為main.xml是一個空白,所以在這就不放上程式碼了
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="ok_label">關閉</string>
<string name="app_name">DemoMenu</string>
<string name="MENU_ABOUT">關於..</string>
<string name="MENU_Refresh">重新整理</string>
<string name="MENU_close">結束</string>
<string name="about_title">關於..</string>
<string name="about_msg">注意!你在看我嗎? \n\n
你可以再近一點! \n\n
你真的可以再近一點! </string>
</resources>
DemoMenuActivity.java
package jim.demo.menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DemoMenuActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//定義三個menu
protected static final int MENU_ABOUT = Menu.FIRST;
protected static final int MENU_Refresh = Menu.FIRST+2;
protected static final int MENU_close = Menu.FIRST+1;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//加入應用程式menu中,分別是:關於我、重新整理、結束
menu.add(0, MENU_ABOUT, 0, getString(R.string.MENU_ABOUT));
menu.add(0, MENU_Refresh, 0, getString(R.string.MENU_Refresh));
menu.add(0, MENU_close, 0, getString(R.string.MENU_close));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId()){
//關於我
case MENU_ABOUT:
//顯示關於我對話方塊
openOptionsDialog();
break;
//重新整理
case MENU_Refresh:
//本頁跳轉到本頁是最簡單的重新整理方式
Intent intent = new Intent();
intent.setClass(DemoMenuActivity.this,DemoMenuActivity.class);
startActivity(intent);
//記得結束掉本頁,不然會出現按下倒退鍵還是在本頁而不是跳出的狀況
this.finish();
break;
//結束
case MENU_close:
finish();
break;
}
return true;
}
private void openOptionsDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(DemoMenuActivity.this);
//標題
dialog.setTitle(R.string.about_title);
//內容
dialog.setMessage(R.string.about_msg);
//中間的關閉按鈕
dialog.setPositiveButton(R.string.ok_label,
new DialogInterface.OnClickListener(){
public void onClick(
DialogInterface dialoginterface, int i){
}
});
//顯示對話方塊
dialog.show();
}
}
執行後畫面
後記:
Menu因為已經是預設的頁面功能了,所以不需要元件,只要加入onCreateOptionsMenu
再設定按下Menu後的事件onOptionsItemSelected就可以了,記得這幾個是寫在onCreate
之外的,有一點值得注意的是我在使用AlertDialog時,內容的換行是可以用"\n\n"
以上為您說明到這,感謝您。


沒有留言:
張貼留言
您的寶貴建議是我前進的動力!