官术网_书友最值得收藏!

Adding action bar action items

The fundamental purpose of an action bar, besides navigation, is to present the user with a set of actions that can be performed.

How to do it...

By simply using the action bar, all the action items are added to the overflow:

  1. The XML for ActionBar items is exactly the same as the options menu:
    <menu ... >
      <item
        android:id="@+id/action_refresh"
        android:icon="@drawable/ic_action_refresh"
        android:title="@string/action_refresh"/>
    </menu>

However, we can customize what items are displayed, and how they are displayed:

  1. To add action items with images to the actual ActionBar property, as well as more complex items, all that is needed is an attribute in the XML, showAsAction:
    <menu ... xmlns:app="http://schemas.android.com/apk/res-auto">
      <item ... app:showAsAction="ifRoom"/>
    </menu>
  2. If we wish to add custom views, such as a search box, to the action bar, we make use of the actionViewClass attribute:
    <menu ... xmlns:app="http://schemas.android.com/apk/res-auto">
      <item ...
      app:actionViewClass="android.support.v7.widget.SearchView"/>
    </menu>
  3. If the view is in a layout resource file, we use the actionLayout attribute:
    <menu ... xmlns:app="http://schemas.android.com/apk/res-auto">
      <item ... app:actionLayout="@layout/action_rating"/>
    </menu>
  4. Sometimes, we may wish to only display the icon initially and then, when the user taps the icon, expand the item to display the action view:
    <menu ... xmlns:app="http://schemas.android.com/apk/res-auto">
      <item ... app:showAsAction="ifRoom|collapseActionView"/>
    </menu>

How it works...

Action item buttons are just traditional options menu items but are optionally always visible on the action bar.

The underlying logic to handle item selections is the same as that for the traditional options menu. No change is required to existing code inside the OnOptionsItemSelected() method.

The value of the showAsAction attribute can be ifRoom, never, or always. This value can optionally be combined, using a pipe, with withText and/or collapseActionView.

主站蜘蛛池模板: 宝丰县| 都匀市| 成都市| 常州市| 兰州市| 阿巴嘎旗| 个旧市| 崇文区| 桃园县| 泰来县| 泌阳县| 思茅市| 古浪县| 霍林郭勒市| 双柏县| 石家庄市| 莱州市| 沅陵县| 喜德县| 武山县| 旺苍县| 南郑县| 沙田区| 太康县| 黎川县| 梁平县| 枣庄市| 辽阳县| 荔波县| 朝阳县| 富民县| 文水县| 凤阳县| 甘孜| 文昌市| 宁远县| 宝山区| 宜君县| 雷山县| 呼和浩特市| 八宿县|