Toolbar-標(biāo)題欄

前言

本篇文章寝贡,盡可能地總結(jié) Toolbar 的知識(shí)點(diǎn)和用法晓勇,

正文

一戳粒、概述

  • Toolbar 是 Android 5.0 之后被谷歌放出來(lái)的力图,是為了替代之前的 ActionBar 役首,

  • Toolbar 不僅繼承了 ActionBar 的所有功能尝丐,而且靈活性很高,可以配合其他控件來(lái)實(shí)現(xiàn)一些 Meterial Design 效果衡奥。

二摊崭、使用

1. 新建一個(gè)項(xiàng)目,看 styles.xml
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
  • 系統(tǒng)默認(rèn)使用主題 : Theme.AppCompat.Light.DarkActionBar

  • 我們之前所有的項(xiàng)目中 自帶的 ActionBar 就是因?yàn)橹付诉@個(gè)主題才出現(xiàn)的杰赛。

2. 修改主題
1.首先要指定一個(gè)不帶 ActionBar 的主題:
  • Theme.AppCompat.Light.NoActionBar 背景為淺色的主題

  • Theme.AppCompat.NoActionBar 背景為深色的主題

  • 本人喜歡淺色主題呢簸,如下所示:

    <style name="AppTheme2" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
2. 主題中各個(gè)屬性的含義:
  • colorPrimary 標(biāo)題欄的顏色
  • colorPrimaryDark 狀態(tài)欄的顏色
  • colorAccent 指定一個(gè)按鈕的顏色,某些控件的選中狀態(tài)也會(huì)選擇這個(gè)顏色
3. 代碼中簡(jiǎn)單使用
1. 在主 Activity 的布局文件中修改如下:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

   <android.support.v7.widget.Toolbar
       android:id="@+id/toolbar"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@color/colorPrimaryDark"
       android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
       app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
       >
   </android.support.v7.widget.Toolbar>


</FrameLayout>

2. Acticity 中的代碼如下:
package io.github.adsuper.meterialtext;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }
}

  • 這里必須使用 findViewById 乏屯,我試過(guò) ButterKnife 根时,效果顯示不出來(lái)
image
3. 實(shí)現(xiàn)效果與 ActionBar 一樣,但是這是 toolbar
4. 添加標(biāo)題辰晕、子標(biāo)題蛤迎、右側(cè) menu 、左側(cè)導(dǎo)航欄圖標(biāo)含友、logo
1. 添加標(biāo)題替裆、子標(biāo)題、窘问、左側(cè)導(dǎo)航欄圖標(biāo)辆童、logo
  • 在 Activity 中進(jìn)行設(shè)置,如下所示:
public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("title");//設(shè)置標(biāo)題
        toolbar.setSubtitle("suntitle");//設(shè)置子標(biāo)題

        toolbar.setLogo(R.mipmap.ic_launcher);//設(shè)置logo
        setSupportActionBar(toolbar);
        //設(shè)置導(dǎo)航欄圖標(biāo)要在 setSupportActionBar 之后
        toolbar.setNavigationIcon(R.drawable.back6);

    }
image
2. 設(shè)置右側(cè) menu 菜單
  • 第一步:右鍵點(diǎn)擊 res 文件夾惠赫,創(chuàng)建 Menu resource file 把鉴,命名為 toolbar.xml,內(nèi)容如下所示:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/set1"
        android:icon="@drawable/setting"
        android:title="11111"
        app:showAsAction="always"></item>
    <item
        android:id="@+id/set2"
        android:icon="@drawable/setting"
        android:title="22222"
        app:showAsAction="ifRoom"></item>
    <item
        android:id="@+id/set3"
        android:icon="@drawable/setting"
        android:title="33333"
        app:showAsAction="never"></item>


</menu>

其中儿咱,always 表示總是顯示在標(biāo)題欄庭砍,ifRoom 表示控件足夠的話顯示在標(biāo)題欄 ,never 表示不顯示在標(biāo)題欄

  • 第二步:重寫(xiě) Activity 中的 onCreateOptionsMenu 方法混埠,填充布局:
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.toolbar,menu);
        return  true;
    }
  • 第三步:重寫(xiě) Activity 中的 onOptionsItemSelected 方法怠缸,響應(yīng) menu 菜單的點(diǎn)擊事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.set1:
                Toast.makeText(getApplicationContext(),"set1",Toast.LENGTH_SHORT).show();
                break;
            case R.id.set2:
                Toast.makeText(getApplicationContext(),"set2",Toast.LENGTH_SHORT).show();
                break;
            case R.id.set3:
                Toast.makeText(getApplicationContext(),"set3",Toast.LENGTH_SHORT).show();
                break;
            case android.R.id.home:
                Toast.makeText(getApplicationContext(),"左側(cè)導(dǎo)航欄圖標(biāo)",Toast.LENGTH_SHORT).show();
                break;
        }


        return true;
    }

其中:android.R.id.home 是左側(cè)導(dǎo)航欄圖標(biāo)的 id

  • 第四步:運(yùn)行結(jié)果如下:
image

由于第三個(gè)圖標(biāo)設(shè)置的是 never 所以沒(méi)有顯示出來(lái) ,點(diǎn)擊最右側(cè)的如表之后,顯示如下:

image

其中,顯示 33333 是因?yàn)?item 中的這條屬性:android:title="33333"

三、擴(kuò)展

1. 最后側(cè)的按鈕點(diǎn)擊之后顯示出來(lái)的 item 西采,將其放在 toolbar 下方

在 styles.xml 中添加以下代碼:

   <!--無(wú)標(biāo)題欄***淺色背景主題-->
    <style name="AppTheme2" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <!--修改 popup menu 的位置罐呼,使其位于 Toolbar 的下方-->
        <item name="actionOverflowMenuStyle">@style/MenuStyle</item>

    </style>
    
    <style name="MenuStyle" parent="Widget.AppCompat.Light.PopupMenu.Overflow">
        <item name="overlapAnchor">false</item>  <!--把該屬性改為fals-->
    </style>

其中鞠柄,AppTheme2 是我們自己用的主題,添加的代碼看注釋即可

運(yùn)行效果如下所示:

image
2. 標(biāo)題居中樣式:
  • 由于 Toolbar 繼承于 ViewGroup 嫉柴,所以可以在其內(nèi)部放入一個(gè) TextView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
        <!--自定義控件-->
        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:gravity="center"
            android:textStyle="bold"
            android:text="自定義標(biāo)題"
            android:textSize="30dp" />


    </android.support.v7.widget.Toolbar>


</RelativeLayout>

  • 在 Activity 中設(shè)置 toolbar.setTitle("");
public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        toolbar = (Toolbar) findViewById(R.id.toolbar);

        toolbar.setTitle("");

        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.back6);

    }
  • 效果如下:
image
3. 左側(cè)顯示 menu 菜單

左側(cè)顯示 menu 主要是使用 android.support.v7.widget.ActionMenuView

  • 第一步:布局文件設(shè)置如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!--android:paddingTop="25dp" 是狀態(tài)欄的高度厌杜,-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:minHeight="?attr/actionBarSize"
        android:paddingTop="25dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
        <!--加入 ActionMenuView-->
        <android.support.v7.widget.ActionMenuView
            android:id="@+id/action_menu_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
        <!--自定義控件-->
        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:gravity="center"
            android:textStyle="bold"
            android:text="自定義標(biāo)題"
            android:textSize="20dp" />


    </android.support.v7.widget.Toolbar>


</RelativeLayout>

  • 第二步:在 menu 菜單中 創(chuàng)建一個(gè)文件用于填充左側(cè) menu ,命名為:toolbar_left_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/left_text_btn"
        android:title=""
        app:actionLayout="@layout/menu_left_text"
        app:showAsAction="always"/>

</menu>

其中计螺,app:actionLayout 屬性表示新建一個(gè) style 布局夯尽,填充這個(gè) item ,主要作用是設(shè)置這個(gè) item 的個(gè)性登馒, @layout/menu_left_text 如下所示:

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

    <TextView
        android:id="@+id/textview"
        android:text="關(guān)閉"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textColor="@color/colorAccent"

        />

</RelativeLayout>
  • 第三步匙握,Activity 中的操作:
public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        
        ActionMenuView actionMenuView = (ActionMenuView) toolbar.findViewById(R.id.action_menu_view);
        //填充 menu 布局
        getMenuInflater().inflate(R.menu.toolbar_left_menu, actionMenuView.getMenu());
        //設(shè)置 item 的點(diǎn)擊事件(沒(méi)有填充布局的 item )
        actionMenuView.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
//                Toast.makeText(getApplicationContext(),"關(guān)閉",Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        // 找到 id 找到對(duì)應(yīng)的 item
        MenuItem menuItem = actionMenuView.getMenu().findItem(R.id.left_text_btn);
        //設(shè)置 對(duì)應(yīng) item 填充布局的點(diǎn)擊事件
        menuItem.getActionView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"關(guān)閉",Toast.LENGTH_SHORT).show();
            }
        });

        toolbar.setTitle("");

        setSupportActionBar(toolbar);

    }
  • 運(yùn)行效果如下所示:


    image

點(diǎn)擊關(guān)閉按鈕會(huì)響應(yīng)對(duì)應(yīng)的 toast

4. Toolbar 之狀態(tài)欄適配方案

詳情參考:帥比張

  • Android 5.0 之前的版本,狀態(tài)欄是黑色的陈轿,之后的狀態(tài)欄是半透明的
1. 在使用的主題文件下添加如下代碼:(要求 API 大于等于 19)
<!--設(shè)置狀態(tài)欄為透明的-->
<item name="android:windowTranslucentStatus">true</item>

或者在 activity 中添加如下代碼

//設(shè)置透明狀態(tài)欄
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }

但是在代碼里聲明更有效圈纺!

2. 在 Toolbar 中添加這么一條屬性
//因?yàn)闋顟B(tài)欄的高度是 25dp
android:paddingTop="25dp"
  • 在 API 19 上顯示為:


    image
  • 在 API 21 上顯示為:


    image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市麦射,隨后出現(xiàn)的幾起案子蛾娶,更是在濱河造成了極大的恐慌,老刑警劉巖潜秋,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蛔琅,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡峻呛,警方通過(guò)查閱死者的電腦和手機(jī)罗售,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)钩述,“玉大人寨躁,你說(shuō)我怎么就攤上這事∏芯啵” “怎么了朽缎?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)谜悟。 經(jīng)常有香客問(wèn)我,道長(zhǎng)北秽,這世上最難降的妖魔是什么葡幸? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮贺氓,結(jié)果婚禮上蔚叨,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好蔑水,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布邢锯。 她就那樣靜靜地躺著,像睡著了一般搀别。 火紅的嫁衣襯著肌膚如雪丹擎。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,165評(píng)論 1 299
  • 那天歇父,我揣著相機(jī)與錄音蒂培,去河邊找鬼。 笑死榜苫,一個(gè)胖子當(dāng)著我的面吹牛护戳,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播垂睬,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼媳荒,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了驹饺?” 一聲冷哼從身側(cè)響起钳枕,我...
    開(kāi)封第一講書(shū)人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎逻淌,沒(méi)想到半個(gè)月后么伯,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡卡儒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年田柔,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片骨望。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡硬爆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出擎鸠,到底是詐尸還是另有隱情缀磕,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布劣光,位于F島的核電站袜蚕,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏绢涡。R本人自食惡果不足惜牲剃,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望雄可。 院中可真熱鬧凿傅,春花似錦缠犀、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至箱残,卻和暖如春滔迈,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背疚宇。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工亡鼠, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人敷待。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓间涵,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親榜揖。 傳聞我的和親對(duì)象是個(gè)殘疾皇子勾哩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容

  • 在開(kāi)發(fā)中經(jīng)常需要使用到標(biāo)題欄,很多時(shí)候我們會(huì)自自定義一個(gè)標(biāo)題欄举哟,因?yàn)樽远x標(biāo)題欄基本上就只需要使用個(gè)Relativ...
    剩下的只有自己閱讀 1,877評(píng)論 0 2
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,077評(píng)論 25 707
  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線程思劳,因...
    小菜c閱讀 6,401評(píng)論 0 17
  • 水霧朦朧 風(fēng)爽靈動(dòng) 河水朗朗 雨燕低行 一支絨花輕捻來(lái) 一顆青松立心懷 一陣清風(fēng)擦身過(guò) 一池清泉蕩漾開(kāi) 如此美景盡...
    舍得_之間閱讀 332評(píng)論 6 8
  • 今天三姨家的弟弟過(guò)來(lái)玩,晚上上好課已經(jīng)七點(diǎn)多了妨猩,緊忙的去吃晚飯潜叛。不知道是家里做的飯菜沒(méi)味道還是外面的飯比較香,媳婦...
    秋景001閱讀 149評(píng)論 0 0