子功能表
子功能表就是將相同功能的分組進行多級顯示的一種菜單。
建立子功能表的步驟:
1、 覆蓋Activity的onCreateOptionsMenu()方法,調用Menu的addSubMenu()方法來添加子功能表
2、 調用SubMenu的add()方法,添加子功能表
3、 覆蓋onContextItemSelected()方法,響應子功能表的單擊事件
至於onCreateOptionsMenu()方法在前面已做過介紹,現在來看下Menu的addSubMenu()方法,與add()方法一樣它有四個重載方法,參數也同出一轍。在這也就不再多說明了
public abstract SubMenu addSubMenu (int groupId, int itemId, int order, CharSequence title)
public abstract SubMenu addSubMenu (int groupId, int itemId, int order, int titleRes)
public abstract SubMenu addSubMenu (CharSequence title)
public abstract SubMenu addSubMenu (int titleRes)
這四個函數的返回對象都是SubMenu,那麼我們就來看下SubMenu吧,隨便來瞭解它的一些屬性及方法:
SubMenu是實現Menu的
比較常用的方法有:setHeaderIcon()、setHeaderTitle()
下面通過兩個執行個體來熟悉下SubMenu
執行個體1:
package com.jiahui.activity;
import java.lang.reflect.Field;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
public class SubMenuDemoActivity extends Activity {
private static final int ITEM1 = Menu.FIRST;
private static final int ITEM2 = Menu.FIRST + 1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu file = menu.addSubMenu("檔案");
SubMenu edit = menu.addSubMenu("編輯");
file.add(0, ITEM1, 0, "建立");
file.add(0, ITEM2, 0, "開啟");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ITEM1:
setTitle("建立檔案");
break;
case ITEM2:
setTitle("開啟檔案");
break;
}
return true;
}
}
效果:
執行個體2:
package com.jiahui.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.SubMenu;
public class SubMenuDemo_2Activity extends Activity {
private static final int UPLOAD=Menu.FIRST;
private static final int DOWNLOAD=Menu.FIRST+1;
private static final int SUB_UPLOAD_A=Menu.FIRST+2;
private static final int SUB_UPLOAD_B=Menu.FIRST+3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu uploadSubMenu=menu.addSubMenu(0, UPLOAD, 0, "上傳");
uploadSubMenu.setIcon(R.drawable.upload);
uploadSubMenu.setHeaderIcon(R.drawable.upload);//設定子功能表的標題
uploadSubMenu.setHeaderTitle("上傳參數設定");//設定子功能表的標題 預設為“上傳”
uploadSubMenu.add(0, SUB_UPLOAD_A, 0, "上傳參數1");
uploadSubMenu.add(0, SUB_UPLOAD_B, 0, "上傳參數2");
SubMenu downloadSubMenu=menu.addSubMenu(0, DOWNLOAD, 0, "下載");
downloadSubMenu.setIcon(R.drawable.download);
return super.onCreateOptionsMenu(menu);
}
}
效果:
摘自:jiahui524專欄