参考《Pro Android 4.0》
ActionBar
11.0之后,ActionBar在Activity中默认存在,可以在代码中设置其显示与否:
ActionBar actionBar = getActionBar(); // Hide the Action Bar actionBar.hide(); // Show the Action Bar actionBar.show();
也可以在Manifest中设置是否显示ActionBar:
<activity android:name=”.MyNonActionBarActivity” android:theme=”@android:style/Theme.Holo.NoActionBar”>
创建一个不显示ActionBar的Theme:
<?xml version=”1.0” encoding=”utf-8”?>
<resources> <style name=”NoActionBar” parent=”@style/ActivityTheme”>
<item name=”android:windowActionBar”>false</item> </style>
</resources>
ActionBar的其他设置:
ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayUseLogoEnabled(displayLogo); actionBar.setDisplayShowHomeEnabled(false); actionBar.setSubtitle(“Inbox”); actionBar.setTitle(“Label:important”); Resources r = getResources();Drawable myDrawable = r.getDrawable(R.drawable.gradient_header); actionBar.setBackgroundDrawable(myDrawable); //ActionBar float above content @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); setContentView(R.layout.main); }
使用ActionBar做导航
新建一个Tab:
Tab tabOne = actionBar.newTab(); tabOne.setText(“First Tab”).setIcon(R.drawable.ic_launcher).setContentDescription(“Tab the First”).setTabListener( new TabListener<MyFragment>(this, R.id.fragmentContainer, MyFragment.class)); actionBar.addTab(tabOne);
实现TabListener接口:
public static class TabListener<T extends Fragment> implements ActionBar.TabListener { private MyFragment fragment; private Activity activity; private Class<T> fragmentClass; private int fragmentContainer;
public TabListener(Activity activity, int fragmentContainer, Class<T> fragmentClass) { this.activity = activity;
this.fragmentContainer = fragmentContainer;
this.fragmentClass = fragmentClass; } // Called when a new tab has been selected
public void onTabSelected(Tab tab, FragmentTransaction ft) { if (fragment == null) {
String fragmentName = fragmentClass.getName();
fragment = (MyFragment)Fragment.instantiate(activity, fragmentName);
ft.add(fragmentContainer, fragment, null);
fragment.setFragmentText(tab.getText()); } else {
ft.attach(fragment); }
} // Called on the currently selected tab when a different tag is selected.
public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (fragment != null) {
ft.detach(fragment); }
}
// Called when the selected tab is selected.public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO React to a selected tab being selected again. } }
将TabListener与Tab绑定在一起:
Tab tabOne = actionBar.newTab(); TabListener<EarthquakeListFragment> listTabListener = new TabListener<EarthquakeListFragment>(this, R.id.EarthquakeFragmentContainer, EarthquakeListFragment.class); tabOne.setTabListener(listTabListener);
使用下拉框导航:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); ArrayList<CharSequence> al = new ArrayList<CharSequence>(); al.add(“Item 1”);al.add(“Item 2”); ArrayAdapter<CharSequence> dropDownAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1, al); // Select the drop-down navigation mode. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); // Create a new Spinner Adapter that contains the values to be displayed in the drop down.
ArrayAdapter dropDownAdapter = ArrayAdapter.createFromResource(this, R.array.my_dropdown_values, android.R.layout.simple_list_item_1); // Assign the callbacks to handle drop-down selections.
actionBar.setListNavigationCallbacks(dropDownAdapter, new OnNavigationListener() {
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Modify your UI based on the position of the drop down item selected. return true; } });
使用菜单和ActionBar Item
Android Actionbar中常用的Menu类型:
1. Icon Menu:在ActionBar中以图标形式显示的Menu
2. Expanded and overflow Menu: 点击more出现的菜单,显示文本而不是图标。
3. Submenu
创建菜单
重写Activity中的onCreateOptionMenus方法可以创建菜单:
static final private int MENU_ITEM = Menu.FIRST; @Override
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Group ID
int groupId = 0;
// Unique Menu Item identifier. Used for event handling int menuItemId = MENU_ITEM;
// The order position of the item
int menuItemOrder = Menu.NONE;
// Text to be displayed for this Menu Item
int menuItemText = R.string.menu_item; // Create the Menu Item and keep a reference to it
MenuItem menuItem = menu.add(groupId, menuItemId, menuItemOrder, menuItemText); return true;
}
创建MenuItem的几个参数:
1. MenuItem所在Group的ID
2. MenuItem的ID,后面可以用findItem方法获取对应的MenuItem
3. MenuItem在组内的顺序
4. MenuItem显示的文本
获取已创建的MenuItem:
MenuItem menuItem = menu.findItem(MENU_ITEM);
设置MenuItem的显示方式
使用setShowAsActionFlags 方法,可以设置MenuItem在ActionBar中的显示:
SHOW_AS_ACTION :永远在ActionBar中显示
SHOW_AS_IF_SPACE :当ActionBar有空白位置的时候显示
MenuItem类型
1. CheckBox:
// Create a new check box item.
menu.add(0, CHECKBOX_ITEM, Menu.NONE, “CheckBox”).setCheckable(true);
2. Radio Buttons:
// Create a radio button group.
menu.add(RB_GROUP, RADIOBUTTON_1, Menu.NONE, “Radiobutton 1”);
menu.add(RB_GROUP, RADIOBUTTON_2, Menu.NONE, “Radiobutton 2”);
menu.add(RB_GROUP, RADIOBUTTON_3, Menu.NONE, “Radiobutton 3”).setChecked(true);
3. 快捷键
// Add a shortcut to this Menu Item, ‘0’ if using the numeric keypad or ‘b’ if using the full keyboard.
menuItem.setShortcut(‘0’, ‘b’);
4. Condensed Title (Condensed Title是指在icon menu的状态下显示的标题,在扩展(more)那里会显示全标题。)
menuItem.setTitleCondensed(“Short Title”);
5. icon
menuItem.setIcon(R.drawable.menu_item_icon);
6. MenuItem Click Listener
menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem _menuItem) { [ ... execute click handling, return true if handled ... ] return true;
} });
7. Intent
menuItem.setIntent(new Intent(this, MyOtherActivity.class));
Action View
menuItem.setActionView(R.layout.my_action_view).setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM|MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
可以在ActionView中加Button等控件:
View myView = menuItem.getActionView();
Button button = (Button)myView.findViewById(R.id.goButton); button.setOnClickListener(new OnClickListener() {
public void onClick(View v) { // TODO React to the button press. } });
从Fragment中获取Menu Item:
在Fragment中调用setHasOptionsMenu方法,可以告诉Activity这个Fragment中含有MenuItem,从而使Activity获得并显示这些MenuItem。
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true);
}
使用XML定义MenuItem
这是目前比较推荐的添加MenuItem的方法,在res/menu中创建XML文件并将MenuItem定义写入此XML:
<menu xmlns:android=”http://schemas.android.com/apk/res/android”>
<item android:id=”@+id/action_item”
android:icon=”@drawable/action_item_icon”
android:title=”@string/action_item_title”
android:showAsAction=”ifRoom”> </item>
<item android:id=”@+id/action_view_item”
android:icon=”@drawable/action_view_icon”
android:title=”@string/action_view_title”
android:showAsAction=”ifRoom|collapseActionView”
android:actionLayout=”@layout/my_action_view”> </item>
<item android:id=”@+id/action_provider_item”
android:title=”Share”
android:showAsAction=”always” android:actionProviderClass=”android.widget.ShareActionProvider”>
</item> <item android:id=”@+id/item02”
android:checkable=”true”
android:title=”@string/menu_item_two”> </item>
<item android:id=”@+id/item03”
android:numericShortcut=”3”
android:alphabeticShortcut=”3”
android:title=”@string/menu_item_three”> </item>
<item android:id=”@+id/item04”
android:title=”@string/submenu_title”>
<menu> <item android:id=”@+id/item05”
android:title=”@string/submenu_item”> </item>
</menu> </item>
</menu>
然后,在onCreateOptionsMenu中创建Menu:
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu); return true;
}
响应Menu选择事件
Activity中所有的Menu事件都是放在onOptionsItemSelected 中一起处理的:
public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); // Find which Menu Item has been selected
switch (item.getItemId()) { // Check for each known Menu Item
case (MENU_ITEM): [ ... Perform menu handler actions ... ]
return true; // Return false if you have not handled the Menu Item default:
return false;
} }
子菜单和环境菜单
创建子菜单:
SubMenu sub = menu.addSubMenu(0, 0, Menu.NONE, “Submenu”);
sub.setHeaderIcon(R.drawable.icon); sub.setIcon(R.drawable.icon);
MenuItem submenuItem = sub.add(0, 0, Menu.NONE, “Submenu Item”);
使用环境菜单和弹出菜单:
一种方法是重写View中的onCreateContextMenu方法,这样任何包含这个View的Activity都会包含这个上下文菜单。
@Override
public void onCreateContextMenu(ContextMenu menu) { super.onCreateContextMenu(menu); menu.add(“ContextMenuItem1”);
}
更常用的方法是重写Activity的onCreateContextMenu方法,然后在onCreate方法中调用.
registerForContextMenu(view): @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EditText view = new EditText(this);
setContentView(view); registerForContextMenu(view); } @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(“Context Menu”);
menu.add(0, Menu.FIRST, Menu.NONE, “Item 1”).setIcon(R.drawable.menu_item);
menu.add(0, Menu.FIRST+1, Menu.NONE, “Item 2”).setCheckable(true);
menu.add(0, Menu.FIRST+2, Menu.NONE, “Item 3”).setShortcut(‘3’, ‘3’);
SubMenu sub = menu.addSubMenu(“Submenu”);sub.add(“Submenu Item”); }
这样,在registerForContextMenu中注册的View中长按屏幕时,就会出现这个环境菜单。
弹出菜单
创建弹出菜单并绑定到View:
final PopupMenu popupMenu = new PopupMenu(this, myView);
创建弹出菜单并绑定到Button:
final PopupMenu popupMenu = new PopupMenu(this, button); popupMenu.inflate(R.menu.my_popup_menu); popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) { case (POPUP_ITEM_1) :
// TODO Handle popup menu clicks.
return true; default:
return false;
} }
});