添加Android的ActionBar

1:添加Actionbar

Actionbar是可以引入到你Activity中的最重要的设计元素之一,它通过提供若干用户接口,和使app之间看起来连贯的方式使你的用户对你App快速熟悉起来。
它的关键功能点包括:
指示用户当在App中的所处位置;
以一种可以预见的方式打开重要的功能(比如搜索);
支持页面导航和页面切换(带Tab页和下拉列表)。
1.1 设置Actionbar
它最基本的形式就是在左侧显示Activity的标题和应用图标,即使在这种最简单的形式中,Actionbar在提示用户在App中所处位置和强烈标识你的App方面也是有用的。
设置一个基本的Actionbar要求你的App使用具有Actionbar能力的主题,但具体是哪个主题取决于你想支持的最低版本,所以,依据你要支持的最低安卓版本,本节课分为两个部分。
1.1.1 支持Android3.0及以上版本
   从3.0(Level11)开始,Actionbar就被包含在所有使用Theme.Holo主题(或者它的子主题)的Activity中了,当把android:minSdkVersion 或者android:targetSdkVersion的属性设置为11或者以上时,Theme.Holo主题就是默认的主题 。所以要添加Actionbar,非常简单,把android:minSdkVersion 或者android:targetSdkVersion的值设置为11及以上就行了。
1.1.2 支持Android2.1及以上版本
在3.0以下版本往Activity中添加Actionbar时,项目需包含Android Support Library,首先添加支持库,一些支持库包含资源文件,而有些不包含:the following sections describe how to add a Support Library with or without resources to your application project.

To add a Support Library without resources to your application project:

添加不包含资源的库时,就是在libs目录下拷入jar包再add to build path 一把。

下面是具体的导入Library的方法,首先是不包资源文件的。

  1. Make sure you have downloaded the Android Support Library using the SDK Manager.
  2. Create a  directory in the root of your application project.
  3. Copy the JAR file from your Android SDK installation directory (e.g., <sdk>/extras/android/support/v4/android-support-v4.) into your application's project directory.
  4. Right click the JAR file and select Build Path > Add to Build Path.

接下来是包含资源文件的

To add a Support Library with resources (such as v7 appcompat for action bar) to your application project:

  1. Create a library project and ensure the required JAR files are included in the project's build path:
  2. Select File > Import.
  3. Select Existing Android Code Into Workspace and click Next.
  4. Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to /extras/android/support/v7/appcompat/.
  5. Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat.
  6. In the new library project, expand the libs/ folder, right-click each  file and select Build Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar android-support-v7-appcompat.jar files to the build path.
  7. Right-click the project and select Build Path > Configure Build Path.
  8. In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar  files.
  9. Uncheck Android Dependencies.
  10. Click OK to complete the changes.
至此,Android Support Library导入完成,在新那的项目中把新Library引入工程中就可以使用了。拉下来:
1,更换Activity的父类,换成ActionBarActivity,例如:
public class MainActivity extends ActionBarActivity { ... }
2、在清单文件中把<applicatioin>元素中使用的主题换成Theme.AppCompat中的其中之一,或者把每个<activity>元素的主题换成Theme.AppCompat中的一个,如果自定义议题,则要把Theme.AppCompat设置为父主题 。
2:添加Action按钮

那些直接出现在Actionbar中,并且带有图标和文字的东西就叫作action buttons,那些没有显示在Actionbar中或者不太重要的Action被隐藏到了action流中。

2.1、在XML文件中指定Acitons

Actions按钮和其它在Action流中可用的item是在menu resource XML文件中定义的,如果要添加actions,需要要工程目录res/menu下新建XML文件。
每添加一个<item>元素,Actionbar中就出现一个item,例如:
res/menu/main_activity_actions.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android: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 -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:showAsAction="never" />
</menu>

上的定义说明:在Actionbar空间够用的情况下,搜索功能必须以一个action按钮的方式在它上面展现,但是Settings就该始终出现的下拉列表中(默认情况下,所有的action都是在下拉列表中的)
icon属性需要一个image的资源ID,同样的title属性来自于工程下res/values目录中一个XML文件的资源。
另外,如果你在使用兼容2.1版本的支持库,showAsAction前面的android:名空间是不可用的,
你需要自定义一个命名空间,并且把它当作showAsAction属性的前缀(一个自定义的XML名空间应该基于你的app名字,但是名字你可以随便起
xmlns:shit="http://schemas.android.com/apk/myapp" 

2.2、把Actions按钮添加到Action Bar中
通过实现回调方法onCreateOptionsMenu(),利用给定的Menu对象渲染目录的资源文件,例如:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}
 
 2.3、给Action按钮添加响应事件

当Action按钮或者Action Overflow中的按钮被点击时,系统会调用activity的onOptionsItemSelected()方法,在此方法的实现中,调用给定MenuItem对象的getItemId()方法得到被点击Item的ID来识别哪个按钮被点击了,这些ID对应于你在MenuXML文件中定义Item项中的ID

@Overridepublic boolean onOptionsItemSelected(MenuItem item) {    // Handle presses on the action bar items    switch (item.getItemId()) {        case R.id.action_search:            openSearch();            return true;        case R.id.action_settings:            openSettings();            return true;        default:            return super.onOptionsItemSelected(item);    }
}
2.4、为低层次的Activity添加向上(返回)按钮

在APP的层级结构中,所有非主页的Activity都应该提供一个导向父页面的按钮,这个按钮就是Actionbar上面的Up键。
不管是运行在Android4.1以上还是使用支持库中的ActionBarActivity,实现向上级导航的操作都清单文件中指定父Activity,并且激活action bar中的Up按钮。

在子Activity中添加parentActivityName 属性,并添加 <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />

例如,像下面一样声明activity的父亲
<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>
下面就是激活ActionBar中的Up按钮,在onCreate()方法中调用setDisplayHomeAsUpEnabled()
:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_displaymessage);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // If your minSdkVersion is 11 or higher, instead use:
如你支持的的最小SDK版本是11,就用下面的方法代替上面。
getActionBar().setDisplayHomeAsUpEnabled(true);
}
3、给ActionBar添加样式

有时候,仅能提供熟悉和可预见的导航方式还是不够的,你需要使你的Actionbar风格最完美的匹配你的产品风格,用Android的style and theme 资源可以很容易的做到这一点。

Android包含一些自带的样式,包括"dark"/"light"action bar 样式,你可以扩展这些样式。

注意:如果使用Actionbar的支持库,就得使用或者复写Theme.AppCompat样式组,(而不是在API11以上使用的Theme.Holo样式组)。这样的话,需要声明的样式都要声明两次,一次是使用platform的样式properties,
(android:properties)一次是使用支持库包含的样式Properties(appcompat.R.attr)详情如下 :

3.1、使用Android 样式
Android有两个指示action bar 颜色的Activity样式基线:
Theme.Holo 黑色的样式
Theme.Holo.Light 白色的样式
在清单文件的<application>或者<activity>结点下声明android:theme属性,就可以为你的整个APP或者单个的Activity应用这些样式 。

例如 :<application android:theme = "@android:style/Theme.Holo.Light"/>
在这种情况下,也可以通过把其中一个Activity的Teme属性设置为Theme.Holo.Light.DarkActionBar使这个Activity的颜色设计为白色。

当然,你要是使用支持库,就得使用Theme.AppCompat样式 :
Theme.AppCompat 黑色样式
Theme.AppCompat.Lignt 白色样式
Theme.AppCompat.Light.DarkActionBar 白色样式中的黑色Actionbar

除此之外,还要注意Action图标颜色与ActionBar颜色的搭配。

3.2、自定义背景
改变Actionbar的背景颜色一般是这样的:
为你的Activity自定义一个样式,更改其中的actionBarStyle属性,这个属性又指向另一个样式(假设是样式a),在样式a中,就可以用自定义的drawable资源来指定background属性了。
如果使用Navigation Tabs 或者split aciton bar 则可以用backgroundStacked 和backgroundSplit属性来指定背景。
注意:为自定义的样式和继承于其它样式的样式指定可用的父样式是非常重要的,如果没有父样式,你的Actionbar就会缺失很多样式属性,除非你一个一个的指定它们。

在Android3.0以上SDK中,我们这样作:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.Holo.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.Holo.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/actionbar_background</item>
    </style>
</resources>
之后应用此样式到你的整个应用或者单个Activity

<application android:theme="@style/CustomActionBarTheme" ... />
在Android2.1以上版本中,设置背景:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/actionbar_background</item>

        <!-- Support library compatibility -->
        <item name="background">@drawable/actionbar_background</item>
    </style>
</resources>
之后应用到Activity
<application android:theme="@style/CustomActionBarTheme" ... />
3.3、自定义文本颜色

需要为每个文本元素更改属性。

更改Activity标题:创建自定义样式,更改actionBarStyle属性为其它的自定义style(假设为样式a),再更改样式a的titleTextStyle属性为样式c,最后更改样式c的textColor属性为需要的值。

更改Activity tabs:在Activity Theme中更改actionBarTabTextStyle
更改Action buttons:更改actionMenuTextColor

在3.0以上的版本中,sytle的XML文件这样写:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.Holo">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="android:actionMenuTextColor">@color/actionbar_text</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.Holo.ActionBar">
        <item name="android:titleTextStyle">@style/MyActionBarTitleText</item>
    </style>

    <!-- ActionBar title text -->
    <style name="MyActionBarTitleText"
           parent="@style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">@color/actionbar_text</item>
    </style>

    <!-- ActionBar tabs text styles -->
    <style name="MyActionBarTabText"
           parent="@style/Widget.Holo.ActionBar.TabText">
        <item name="android:textColor">@color/actionbar_text</item>
    </style>
</resources>
在2.1以上版本中,XML文件这样写:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="android:actionMenuTextColor">@color/actionbar_text</item>

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="actionMenuTextColor">@color/actionbar_text</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.AppCompat.ActionBar">
        <item name="android:titleTextStyle">@style/MyActionBarTitleText</item>

        <!-- Support library compatibility -->
        <item name="titleTextStyle">@style/MyActionBarTitleText</item>
    </style>

    <!-- ActionBar title text -->
    <style name="MyActionBarTitleText"
           parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">@color/actionbar_text</item>
        <!-- The textColor property is backward compatible with the Support Library -->
    </style>
    <!-- ActionBar tabs text -->
    <style name="MyActionBarTabText"
           parent="@style/Widget.AppCompat.ActionBar.TabText">
        <item name="android:textColor">@color/actionbar_text</item>
        <!-- The textColor property is backward compatible with the Support Library -->
    </style>
</resources>
 
3.4、自定义Tab标签
在res/values/目录下,创建自定义样式,更改actionBarTabStyle属性,这个属性指向另一个style,在这个style中,更改background属性为一系列的drawable(state-list drawable
state-list drawable是这样的东西:当前被选中的标签的背景不同于其它标签,也就是选择器,selector,位于drawable目录下,例如下面的:

res/drawable/actionbar_tab_indicator.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- STATES WHEN BUTTON IS NOT PRESSED -->

    <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false"
          android:state_pressed="false"
          android:drawable="@drawable/tab_unselected" />
    <item android:state_focused="false" android:state_selected="true"
          android:state_pressed="false"
          android:drawable="@drawable/tab_selected" />

    <!-- Focused states (such as when focused with a d-pad or mouse hover) -->
    <item android:state_focused="true" android:state_selected="false"
          android:state_pressed="false"
          android:drawable="@drawable/tab_unselected_focused" />
    <item android:state_focused="true" android:state_selected="true"
          android:state_pressed="false"
          android:drawable="@drawable/tab_selected_focused" />


<!-- STATES WHEN BUTTON IS PRESSED -->

    <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false"
          android:state_pressed="true"
          android:drawable="@drawable/tab_unselected_pressed" />
    <item android:state_focused="false" android:state_selected="true"
        android:state_pressed="true"
        android:drawable="@drawable/tab_selected_pressed" />

    <!-- Focused states (such as when focused with a d-pad or mouse hover) -->
    <item android:state_focused="true" android:state_selected="false"
          android:state_pressed="true"
          android:drawable="@drawable/tab_unselected_pressed" />
    <item android:state_focused="true" android:state_selected="true"
          android:state_pressed="true"
          android:drawable="@drawable/tab_selected_pressed" />
</selector>
在3.0以上版本中,自定义Tab标签
res/values/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.Holo">
        <item name="android:actionBarTabStyle">@style/MyActionBarTabs</item>
    </style>

    <!-- ActionBar tabs styles -->
    <style name="MyActionBarTabs"
           parent="@style/Widget.Holo.ActionBar.TabView">
        <!-- tab indicator -->
        <item name="android:background">@drawable/actionbar_tab_indicator</item>
    </style>
</resources>
在2.1以上版本中,
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat">
        <item name="android:actionBarTabStyle">@style/MyActionBarTabs</item>

        <!-- Support library compatibility -->
        <item name="actionBarTabStyle">@style/MyActionBarTabs</item>
    </style>

    <!-- ActionBar tabs styles -->
    <style name="MyActionBarTabs"
           parent="@style/Widget.AppCompat.ActionBar.TabView">
        <!-- tab indicator -->
        <item name="android:background">@drawable/actionbar_tab_indicator</item>

        <!-- Support library compatibility -->
        <item name="background">@drawable/actionbar_tab_indicator</item>
    </style>
</resources>

4、和页面重叠显示的Actionbar

默认情况下,action bar 显示在activity窗口的顶部,减少了整个布局的可用空间,
如果在与用户交互的时候,你还想隐藏和显示bar 可以这样做:调用actionBar对象的hide()方法和show()方法,

然而,这样会引起activity基于新的布局进行重新计算和重新绘图。
为了避免布局重构,可以启用action bar 的overlay mode.在这种模式下,activity布局使用的是整个屏幕空间,

就好像action bar 不在那一样,系统会在页面布局的前方画出action bar,这只是遮盖了一部分上面的布局,

但是现在action bar 隐藏或显示的时候,系统就不会对布局重构了,并且整个过渡是无缝的。
TIP:如果你想把action bar设置为透明的,创建一个带透明背景的自定义的样式。

4.1、开启Overlay模式

自定义一个样式,继承已有的样式,设置android:windowActionBarOverlay属性为true.
3.0以上版本:<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@android:style/Theme.Holo">
        <item name="android:windowActionBarOverlay">true</item>
    </style>
</resources>
3.0以下,2.1以上版本

<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@android:style/Theme.AppCompat">
        <item name="android:windowActionBarOverlay">true</item>

        <!-- Support library compatibility -->
        <item name="windowActionBarOverlay">true</item>
    </style>
</resources>
正如之前所说的那样,上面的样式中,windowActionBarOverlay属性有两个定义,一个是带andord:前缀的,是对应于包含样式的版本平台;一个不带前缀,对应于老版本,系统从支持库中读取样式。
4.2指定布局的上边距
当Actionbar处于Overlay模式下时,毕竟会遮挡一部分后面的内容,如果这些被遮挡的内容必要被显示,那就要保证布局相对于屏幕的上边距等于action bar 的高度。即设置layout 的paddingTop或者marginTop等于action bar的Height。<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?android:attr/actionBarSize">
    ...
</RelativeLayout>
如果使用支持库,向下兼容3.0以下版本,android:这个前缀就不能用了:<!-- Support library compatibility -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">
    ...
</RelativeLayout>
这种情况下,没有前缀的值:attr/actionBarSize可以应用于Android的所有版本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值