In its most basic form, the action bar displays the title for the activity and the app icon on the left. Even in this simple form, the action bar is useful for all activities to inform users about where they are and to maintain a consistent identity for your app.

Figure 1. An action bar with the app icon and activity title.

Suport Android2.1 or Above

Adding the action bar when running on versions older than Android 3.0 (down to Android 2.1) requires that you include the Android Support Library (the v7 appcompat library)in your application.

Once you have the Support Library integrated with your app project:

  1. Update your activity so that it extends ActionBarActivity. For example:

    publicclassMainActivityextendsActionBarActivity{...}
  2. In your manifest file, update either the <application> element or individual <activity> elements to use one of the Theme.AppCompat themes. For example:
    <activityandroid:theme="@style/Theme.AppCompat.Light" ... >

    Note: If you've created a custom theme, be sure it uses one of the Theme.AppCompat themes as its parent. For details, see Styling the Action Bar.

Now your activity includes the action bar when running on Android 2.1 (API level 7) or higher.

Remember to properly set your app's API level support in the manifest:

<manifest ... >
    <uses-sdkandroid:minSdkVersion="7"  android:targetSdkVersion="18"/>
    ...
</manifest>

Adding Action Buttons

The action bar allows you to add buttons for the most important action items relating to the app's current context. Those that appear directly in the action bar with an icon and/or text are known as action buttons. Actions that can't fit in the action bar or aren't important enough are hidden in the action overflow.

Figure 1. An action bar with an action button for Search and the action overflow, which reveals additional actions.

All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory.

Add an <item> element for each item you want to include in the action bar. For example:

res/menu/main_activity_actions.xml

<menuxmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Search, should appear as action button -->
    <itemandroid:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          android:showAsAction="ifRoom"/>
    <!-- Settings, should always be in the overflow -->
    <itemandroid:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:showAsAction="never"/>
</menu>

Download action bar icons

To best match the Android iconography guidelines, you should use icons provided in the Action Bar Icon Pack.

This declares that the Search action should appear as an action button when room is available in the action bar, but the Settings action should always appear in the overflow. (By default, all actions appear in the overflow, but it's good practice to explicitly declare your design intentions for each action.)

If your app is using the Support Library for compatibility on versions as low as Android 2.1, the showAsAction attribute is not available from the android: namespace. Instead this attribute is provided by the Support Library and you must define your own XML namespace and use that namespace as the attribute prefix. (A custom XML namespace should be based on your app name, but it can be any name you want and is only accessible within the scope of the file in which you declare it.) For example:

res/menu/main_activity_actions.xml

<menuxmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:yourapp="http://schemas.android.com/apk/res-auto">
    <!-- Search, should appear as action button -->
    <itemandroid:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          yourapp:showAsAction="ifRoom"  />
    ...
</menu>

To place the menu items into the action bar, implement the onCreateOptionsMenu() callback method in your activity to inflate the menu resource into the given Menu object. For example:

@Override
publicboolean onCreateOptionsMenu(Menu menu){
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    returnsuper.onCreateOptionsMenu(menu);
}

When the user presses one of the action buttons or another item in the action overflow, the system calls your activity's onOptionsItemSelected() callback method. In your implementation of this method, call getItemId() on the given MenuItem to determine which item was pressed—the returned ID matches the value you declared in the corresponding <item> element's android:id attribute.

@Override
publicboolean onOptionsItemSelected(MenuItem item){
    // Handle presses on the action bar items
    switch(item.getItemId()){
        case R.id.action_search:
            openSearch();
            returntrue;
        case R.id.action_settings:
            openSettings();
            returntrue;
        default:
            returnsuper.onOptionsItemSelected(item);
    }
}

All screens in your app that are not the main entrance to your app (activities that are not the "home" screen) should offer the user a way to navigate to the logical parent screen in the app's hierarchy by pressing the Up button in the action bar.

When running on Android 4.1 (API level 16) or higher, or when using ActionBarActivity from the Support Library, performing Up navigation simply requires that you declare the parent activity in the manifest file and enable the Up button for the action bar.

For example, here's how you can declare an activity's parent in the manifest:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity">
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity"/>
    </activity>
</application>

Then enable the app icon as the Up button by calling setDisplayHomeAsUpEnabled():

@Override
publicvoid onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_displaymessage);     getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // If your minSdkVersion is 11 or higher, instead use:
    // getActionBar().setDisplayHomeAsUpEnabled(true);
}

Because the system now knows MainActivity is the parent activity for DisplayMessageActivity, when the user presses the Up button, the system navigates to the parent activity as appropriate—you do not need to handle the Up button's event.

 

The First Android App----Adding the Action Bar的更多相关文章

  1. Android官方文档翻译 七 2.Adding the Action Bar

    Adding the Action Bar 增加一个Action Bar(工具栏) The action bar is one of the most important design element ...

  2. Android 自定义title 之Action Bar

    Android 自定义title 之Action Bar 2014-06-29  飞鹰飞龙...  摘自 博客园  阅 10519  转 25 转藏到我的图书馆   微信分享:   Action Ba ...

  3. 学习android文档 -- Adding the Action Bar

    1. Setting Up the Action Bar:users-sdk version 11以上可以使用holo主题:如果不使用holo主题,或者sdk版本较低,则需要在manifest文件的& ...

  4. Android开发UI之Action Bar

    郭大神的讲解:http://blog.csdn.net/guolin_blog/article/details/18234477 官网链接:http://developer.android.com/i ...

  5. Android UI ActionBar功能-Action Bar 左上角的向上或返回按钮

    ActionBar在左上角还提供了一个向上或返回的按钮,默认情况下是隐藏的需要在代码中开启: 官方文档:http://wear.techbrood.com/training/basics/action ...

  6. 【Android】Android之Action Bar

    Action Bar是在窗口上指示用户位置的组件,同时给用户提供导航和操作.使用Action Bar可以让你的应用在不同配置的屏幕上看起来比较一致.在开始之前,先了解一些相关的术语: Action B ...

  7. Android训练课程(Android Training) - 添加活动栏(使用action bar)

    2014-10-28 张云飞VIR 翻译自:https://developer.android.com/training/basics/actionbar/index.html 添加活动栏(Addin ...

  8. Android设计和开发系列第二篇:Action Bar(Develop—Training)

    Adding the Action Bar GET STARTED DEPENDENCIES AND PREREQUISITES Android 2.1 or higher YOU SHOULD AL ...

  9. Android设计和开发系列第二篇:Action Bar(Develop—API Guides)

    Action Bar IN THIS DOCUMENT Adding the Action Bar Removing the action bar Using a logo instead of an ...

随机推荐

  1. Why ExerciseAlone May Not Be the Key to Weight Loss

    加强运动也许并不能减肥Why ExerciseAlone May Not Be the Key to Weight LossIf you give a mouse a running wheel, i ...

  2. maven配置国内镜像库

    https://www.cnblogs.com/xiongxx/p/6057558.html

  3. 如何快速实现一个command

    新建一个类,实现icoomand接口 定义一个委托,为测试方便,先不考虑CanExecute的情况. 越简单越好. 代码如下: public class ExitHandler : ICommand ...

  4. luoguP1196(带权并查集)

    题目链接:https://www.luogu.org/problemnew/show/P1196 思路: 带权并查集.对每个结点,构造表示该结点的头结点,该结点距头结点的距离,该列的大小3个数组. 在 ...

  5. GridView控件中的一些常见问题

    1. 无法获取模板列中的值,使用FindControl()方法无效: 给模板列中添加隐藏域,并给隐藏域绑定要获取的值,代码如下: <asp:HiddenField ID="hfIsFr ...

  6. 蚁群算法(Java)tsp问题

      1.理论概述 1.1.TSP问题 旅行商问题,即TSP问题(旅行推销员问题.货郎担问题),是数学领域中著名问题之一.假设有一个旅行商人要拜访n个城市,他必须选择所要走的路径,路径的限制是每个城市只 ...

  7. 【校招面试 之 C/C++】第8题 C++中的静态绑定与动态绑定

    转自:https://blog.csdn.net/chgaowei/article/details/6427731   做了部分修改 为了支持c++的多态性,才用了动态绑定和静态绑定.理解他们的区别有 ...

  8. 基于快速排序的数组划分:2组 3组 K组(sort color)大小写排序 · Partition Array

    2组: [抄题]: 给出一个整数数组 nums 和一个整数 k.划分数组(即移动数组 nums 中的元素),使得: 所有小于k的元素移到左边 所有大于等于k的元素移到右边 返回数组划分的位置,即数组中 ...

  9. HashMap的hash冲突解决方案

    Hash函数 非哈希表的特点:关键字在表中的位置和它之间不存在一个确定的关系,查找的过程为给定值一次和各个关键字进行比较,查找的效率取决于和给定值进行比较的次数. 哈希表的特点:关键字在表中位置和它之 ...

  10. 41-json.decoder.JSONDecodeError: Invalid control character at: line 6894 column 12 (char 186418)

    在使用python中将单词本的单词用正则匹配成字典后,以json存储,仪json读入,但是一直报错: 原因是: 正则处理后的数据有的出了点问题,导致一个字典的 有多个相同的键!!!,则肯定会报错啊!! ...