Android5.0之Toobar的使用

來源:互聯網
上載者:User

Android5.0之Toobar的使用

總體上來說,Toolbar的使用可以分為兩個方面,一方面是將ToolBar當作ActionBar來用,另一方面就是將Toolbar當成一個單獨的控制項來用,不過到目前為止我見到的大部分情況都是把Toolbar當作ActionBar來用,下面我們分別就這兩種使用方式來進行說明。

1.Toolbar作為ActionBar使用

將Toolbar當作ActionBar使用首先要隱藏系統預設的ActionBar,隱藏方式其實很簡單,只需要簡單設定一下style就可以了,如下了:

<style name="AppTheme.NoActionBar">        <item name="android:windowActionBar">false</item>        <item name="android:windowNoTitle">true</item>        <item name="windowActionBar">false</item>        <item name="windowNoTitle">true</item></style>
Android手機在3.0之前標題列叫做titlebar,3.0之後又推出了ActionBar來代替titlebar,所以我們在使用的Toolbar的時候為了相容早期的手機也要把titlebar隱藏掉。這兩個東東都隱藏之後,在資訊清單檔中給Activity或者App設定一下主題就可以了,我這裡給Activity設定主題,如下:
        <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">            <intent-filter>                <action android:name="android.intent.action.MAIN">                <category android:name="android.intent.category.LAUNCHER">            </category></action></intent-filter>        </activity>

如此,我的MainActivity就成功的隱藏掉了ActionBar了,接下來就是怎麼添加Toolbar了,我們知道在企業開發中ActionBar使用並不多,一個重要的原因就是這個東西太死板了,而且太醜了,那麼Google推出Toolbar必然就要避免這些問題,so,Toolbar除了好看另一個最大的優點就是靈活,你完全可以把它當作一個普普通通的控制項來使用,普通控制項怎麼使用呢?先在布局檔案中寫唄,同時,我們為了相容Android5.0之前的手機,在使用Toolbar的時候都是使用v7包裡的Toolbar,布局檔案如下:
<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="org.mobiletrain.toolbar2.MainActivity">    <android.support.v7.widget.toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorPrimary" android:popuptheme="@style/AppTheme.PopupOverlay">    </android.support.v7.widget.toolbar></linearlayout>

OK,是不是很簡單呢?一個簡單的布局檔案就搞定了,那麼這裡有三個地方需要給大家解釋一下,首先是toolbar的高,你可以給一個固定值,也可以參考之前ActionBar的高度,參考ActionBar高度的好處是系統會在不同的裝置上自動為你調整Toolbar的高度。第二點就是background屬性,使用toolbar時我們可以給toolbar設定一個背景顏色。第三就是popupTheme屬性,就是彈出框的顯示,這裡我們一般按如下的方式來設定:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.