第一行代碼讀書筆記 12 -- Material Design 實(shí)戰(zhàn)

本篇文章主要介紹以下幾個知識點(diǎn):

  • Toolbar
  • 滑動菜單
  • 懸浮按鈕
  • 卡片式布局
  • 下拉刷新
  • 可折疊式標(biāo)題欄
蒙奇·D·路飛

Material Design 是由谷歌的設(shè)計(jì)工程師基于優(yōu)秀的設(shè)計(jì)原則,結(jié)合豐富的創(chuàng)意和科學(xué)技術(shù)所發(fā)明的一套全新的界面設(shè)計(jì)語言,包含了視覺、運(yùn)動、互動效果等特性。

在2015年的 Google I/O 大會上推出了一個 Design Support 庫,這個庫將 Material Design 中最具代表性的一些控件和效果進(jìn)行了封裝,使開發(fā)者能輕松地將自己的應(yīng)用 Material 化。本篇文章就來學(xué)習(xí)下 Design Support 這個庫,實(shí)現(xiàn)以下效果:

Material Design

12.1 Toolbar

相信大家熟悉控件 ActionBar,由于其設(shè)計(jì)的原因,被限定只能位于活動的頂部,從而不能實(shí)現(xiàn)一些 Material Design 的效果,因此官方已不建議使用 ActionBar 了,而推薦使用 Toolbar

Toolbar 不僅繼承了 ActionBar 的所有功能,而且靈活性很高。下面來具體學(xué)習(xí)下。

首先,修改一下項(xiàng)目的默認(rèn)主題,指定為不帶 ActionBar 的主題,打開 values 文件下的 styles.xml,修改如下:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" 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>

</resources>

觀察下 AppTheme 中的屬性重寫,3個屬性代表的顏色位置如下:

各屬性指定顏色的位置

把 ActionBar 隱藏起來后,用 ToolBar 來替代 ActionBar,修改布局中的代碼如下:

<?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="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

</FrameLayout>

上述代碼指定一個 xmlns:app 的命名空間是由于很多 Meterial 屬性在5.0之前的系統(tǒng)中并不存在,為了能夠兼容之前的老系統(tǒng),應(yīng)該使用 app:attribute 這樣的寫法,從而就可以兼容 Android 5.0 以下的系統(tǒng)了。

接下來修改活動中的代碼如下:

public class MaterialDesignActivity extends AppCompatActivity {

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);// 將 Toolbar 的實(shí)例傳入
    }
}

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

Toolbar 的標(biāo)準(zhǔn)界面

上面效果和之前的標(biāo)題欄差不多,接下來學(xué)習(xí)一下 Toolbar 常用的功能,比如修改標(biāo)題欄上顯示的文字內(nèi)容。這文字內(nèi)容是在 AndroidManifest.xml 中指定的,如下:

<activity 
    android:name=".chapter12.MaterialDesignActivity"
    android:label="Fruits"/>

上面給 activity 增加了一個 android:label 屬性,指定在 Toolbar 中顯示的文字內(nèi)容,若沒指定的話,默認(rèn)使用 application 中指定的 label 內(nèi)容,即應(yīng)用名稱。

接下來再添加一些 action 按鈕使 Toolbar 更加豐富一些。右擊 res 目錄→New→Directory,創(chuàng)建一個 menu 文件夾。然后右擊 menu 文件夾→New→Menu resource file,創(chuàng)建一個toolbar.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>標(biāo)簽定義 action 按鈕
         android:id 按鈕id;android:icon 按鈕圖標(biāo);android:title 按鈕文字
         app:showAsAction 按鈕的顯示位置:
             always 永遠(yuǎn)顯示在Toolbar中,若屏幕不夠則不顯示
             ifRoom 屏幕空間足夠時顯示在Toolbar中,不夠時顯示在菜單中
             never 永遠(yuǎn)顯示在菜單中
        (Toolbar中的action只顯示圖標(biāo),菜單中的action只顯示文字)-->
    <item
        android:id="@+id/backup"
        android:icon="@mipmap/backup"
        android:title="Backup"
        app:showAsAction="always"/>

    <item
        android:id="@+id/delete"
        android:icon="@mipmap/delete"
        android:title="Delete"
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/settings"
        android:icon="@mipmap/settings"
        android:title="Settings"
        app:showAsAction="never"/>
</menu>

然后修改活動中的代碼如下:

public class MaterialDesignActivity extends AppCompatActivity {

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);// 將 Toolbar 的實(shí)例傳入
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 加載菜單
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 設(shè)置點(diǎn)擊事件
        switch (item.getItemId()){
            case R.id.backup:
                ToastUtils.showShort("點(diǎn)擊了備份");
                break;
            case R.id.delete:
                ToastUtils.showShort("點(diǎn)擊了刪除");
                break;
            case R.id.settings:
                ToastUtils.showShort("點(diǎn)擊了設(shè)置");
                break;
        }
        return true;
    }
}

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

帶有 action 按鈕的 Toolbar

好了,關(guān)于 Toolbar 的內(nèi)容就先講到這。當(dāng)然 Toolbar 的功能遠(yuǎn)遠(yuǎn)不只這些,更多功能以后再挖掘。

12.2 滑動菜單

滑動菜單可以說是 Meterial Design 中最常見的效果之一,將一些菜單項(xiàng)隱藏起來,而不是放置在主屏幕上,通過滑動的方式將菜單顯示出來。

12.2.1 DrawerLayout

谷歌提供了一個 DrawerLayout 控件,借助這個控件,實(shí)現(xiàn)滑動菜單簡單又方便。下面介紹下它的用法。

首先它是一個布局,在布局中允許放入兩個直接子控件,第一個子控件是主屏幕中顯示的內(nèi)容,第二個子控件是滑動菜單顯示的內(nèi)容。因此,可以修改布局代碼如下所示:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--********** 第一個子控件 主屏幕顯示 ***********-->
    <FrameLayout
        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="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </FrameLayout>

    <!--********** 第二個子控件 滑動菜單顯示 **********-->
    <!-- 注意:屬性 android:layout_gravity 是必須指定的 -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:text="這是滑動菜單" 
        android:background="#fff"/>
    
</android.support.v4.widget.DrawerLayout>

接下來在 Toolbar 的最左邊加入一個導(dǎo)航按鈕,提示用戶屏幕左側(cè)邊緣是可以拖動的,點(diǎn)擊按鈕將滑動菜單的內(nèi)容展示出來。修改活動中的代碼如下:

public class MaterialDesignActivity extends AppCompatActivity {
    
    private DrawerLayout mDrawerLayout;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);// 將 Toolbar 的實(shí)例傳入
        
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true); //讓導(dǎo)航按鈕顯示出來
            actionBar.setHomeAsUpIndicator(R.mipmap.menu);//設(shè)置導(dǎo)航按鈕圖標(biāo)
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 加載菜單
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 設(shè)置點(diǎn)擊事件
        switch (item.getItemId()){
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);//打開抽屜
                break;
            
            . . .
        }
        return true;
    }
}

上述代碼值得注意的是在 onOptionItemSelected() 方法中對 HomeAsUp 按鈕的點(diǎn)擊事件進(jìn)行處理,HomeAsUp 按鈕的 id永遠(yuǎn)是 android.R.id.home。現(xiàn)在重新運(yùn)行程序,效果如下:

顯示滑動菜單界面

12.2.2 NavigationView

上面已經(jīng)成功實(shí)現(xiàn)了滑動菜單功能,但界面不美觀,谷歌給我們提供了一種更好的方法——使用 NavigationView,在滑動菜單頁面定制任意布局。

NavigationView 是 Design Support 庫中提供的一個控件,嚴(yán)格按照 Material Design 的要求來設(shè)計(jì)的,并且將滑動菜單頁面的實(shí)現(xiàn)變得非常簡單。下面一起來學(xué)習(xí)下。

首先,將 Design Support 庫以及開源項(xiàng)目 CircleImageView(實(shí)現(xiàn)圖片圓形化,項(xiàng)目主頁地址:https://github.com/hdodenhof/CircleImageView )引入到項(xiàng)目中:

compile 'com.android.support:design:24.2.1'
compile 'de.hdodenhof:circleimageview:2.1.0'

在使用 NavigationView 之前,還需要準(zhǔn)備兩個東西:在 NavigationView 中用來顯示具體菜單項(xiàng)的 menu 和顯示頭部布局的 headerLayout

(1)準(zhǔn)備 menu。在 menu 文件夾下創(chuàng)建一個 nav_menu.xml 文件,編寫代碼如下:

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

    <!--checkableBehavior指定為single表示組中的所有菜單項(xiàng)只能單選 -->
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_call"
            android:icon="@mipmap/call"
            android:title="Call"/>
        <item
            android:id="@+id/nav_friends"
            android:icon="@mipmap/friends"
            android:title="Friends"/>
        <item
            android:id="@+id/nav_location"
            android:icon="@mipmap/location"
            android:title="Location"/>
        <item
            android:id="@+id/nav_mail"
            android:icon="@mipmap/mail"
            android:title="Mail"/>
        <item
            android:id="@+id/nav_task"
            android:icon="@mipmap/task"
            android:title="Task"/>
    </group>
</menu>

(2)準(zhǔn)備 headerLayout。在 layout 文件夾下創(chuàng)建一個布局文件 nav_header.xml,編寫代碼如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:padding="10dp"
    android:background="?attr/colorPrimary">

    <!--*************** 頭像 ****************-->
    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/icon_image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@mipmap/nav_icon"
        android:layout_centerInParent="true"/>
    
    <!--*************** 郵箱 ****************-->
    <TextView
        android:id="@+id/mail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:text="KXwonderful@gmail.com"
        android:textColor="@color/white"
        android:textSize="14sp"/>

    <!--*************** 用戶名 ****************-->
    <TextView
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/mail"
        android:gravity="center"
        android:text="開心wonderful"
        android:textColor="@color/white"
        android:textSize="14sp"/>

</RelativeLayout>

準(zhǔn)備好 menu 和 headerLayout 后,可以使用 NavigationView 了,修改布局代碼,將之前的 TextView 替換成 NavigationView,如下:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--******** 第一個子控件 主屏幕顯示 ********-->
    <FrameLayout
        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="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </FrameLayout>

    <!--******** 第二個子控件 滑動菜單顯示 ********-->
    <!-- 注意:屬性 android:layout_gravity 是必須指定的 -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/nav_menu"
        app:headerLayout="@layout/nav_header"/>

</android.support.v4.widget.DrawerLayout>

最后,修改活動中的代碼,添加處理菜單項(xiàng)的點(diǎn)擊事件,如下:

public class MaterialDesignActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);// 將 Toolbar 的實(shí)例傳入

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true); //讓導(dǎo)航按鈕顯示出來
            actionBar.setHomeAsUpIndicator(R.mipmap.menu);//設(shè)置導(dǎo)航按鈕圖標(biāo)
        }
        navView.setCheckedItem(R.id.nav_call);//設(shè)置默認(rèn)選中項(xiàng)
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                mDrawerLayout.closeDrawers();//關(guān)閉抽屜
                ToastUtils.showShort("點(diǎn)擊了"+item.getTitle());
                return true;
            }
        });
    }

    . . .
}

現(xiàn)在重新運(yùn)行下程序,效果如下:

NavigationView 界面

上面效果相對之前的美觀了許多,但不要滿足現(xiàn)狀,跟緊腳步,繼續(xù)學(xué)習(xí)。

12.3 懸浮按鈕和可交互提示

立體設(shè)計(jì)是 Material Design 中一條非常重要的思想,即應(yīng)用程序的界面不僅僅是一個平面,而應(yīng)該是有立體效果的。

12.3.1 FloatingActionButton

FloatingActionButton 是 Design Support 庫中提供的一個控件,可以比較輕松地實(shí)現(xiàn)懸浮按鈕地效果。它默認(rèn)使用 colorAccent 作為按鈕的顏色。下面來具體實(shí)現(xiàn)下。

首先,在主屏幕布局加入一個 FloatingActionButton,修改布局代碼如下:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--******** 第一個子控件 主屏幕顯示 ********-->
    <FrameLayout
        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="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <!-- app:elevation屬性是給FloatingActionButton指定高度,
            值越大,投影范圍越大,效果越淡,反之 -->
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp"
            android:src="@mipmap/done"
            app:elevation="8dp"/>
    </FrameLayout>

    . . .

</android.support.v4.widget.DrawerLayout>

接著,設(shè)置 FloatingActionButton 的點(diǎn)擊事件,在活動中添加代碼如下:

public class MaterialDesignActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_design);
        . . .
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showShort("點(diǎn)擊了懸浮按鈕");
            }
        });
    }
    . . .
}

現(xiàn)在重新運(yùn)行下程序,效果如下:

FloatingActionButton 的效果

12.3.2 Snackbar

接下來學(xué)習(xí)下 Design Support 庫提供的比 Toast 更加先進(jìn)的提示工具——Snackbar

當(dāng)然,Snackbar 并不是 Toast 的替代品,它們兩者之間有著不同的應(yīng)用場景。Snackbar 在提示當(dāng)中加入了一個可交互按鈕,點(diǎn)擊時可以執(zhí)行一些額外的操作。

Snackbar 的用法非常簡單,修改活動中的代碼如下:

public class MaterialDesignActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_design);
        . . .
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //ToastUtils.showShort("點(diǎn)擊了懸浮按鈕");
                Snackbar.make(v,"刪除數(shù)據(jù)",Snackbar.LENGTH_SHORT)
                        .setAction("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ToastUtils.showShort("數(shù)據(jù)恢復(fù)");
                            }
                        }).show();
            }
        });
    }
    . . .
}

現(xiàn)在重新運(yùn)行下程序,效果如下:

Snackbar 的效果

可以看到,Snackbar 從屏幕底部出現(xiàn),上面有設(shè)置的提示文字和設(shè)置的取消按鈕。但存在個 bug,這個 Snackbar 把懸浮按鈕給遮擋住了,解決這個 bug 就要借助 CoordinatorLayout 了。

12.3.3 CoordinatorLayout

CoordinatorLayout 是 Design Support 庫提供的一個加強(qiáng)版的 FrameLayout 布局,它可以監(jiān)聽其所有子控件的各種事件,然后自動幫我們做出最為合理的響應(yīng)。

CoordinatorLayout 的使用也非常簡單,只需將原來的 FrameLayout 替換一下就可以了。修改布局代碼如下:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--******** 第一個子控件 主屏幕顯示 ********-->
    <android.support.design.widget.CoordinatorLayout
        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="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp"
            android:src="@mipmap/done"
            app:elevation="8dp"/>
    </android.support.design.widget.CoordinatorLayout>

    . . .

</android.support.v4.widget.DrawerLayout>

現(xiàn)在重新運(yùn)行下程序,效果如下:

CoordinatorLayout 自動將懸浮按鈕上移

可以看到懸浮按鈕自動向上移,從而不會被遮住。

上面 Snackbar 好像并不是 CoordinatorLayout 的子控件,卻也能被監(jiān)聽到,是因?yàn)樵?Snackbar 中傳入的第一個參數(shù)是用來指定 Snackbar 是基于哪個 View 來觸發(fā)的,上面?zhèn)魅氲氖?FloatingActionButton 本身,而 FloatingActionButton 是 CoordinatorLayout 的子控件。

12.4 卡片式布局

卡片式布局是 Material Design 中提出的一個新概念,它可以讓頁面中的元素看起來就像在卡片中一樣,并且還能擁有圓角和投影。

12.4.1 CardView

CardView 是 appcompat-v7 庫提供的用于實(shí)現(xiàn)卡片式布局效果的重要控件,它也是一個 FrameLayout,只是額外提供了圓角和陰影等效果,有立體感。

CardView 的基本用法非常簡單,如下:

<!-- app:cardCornerRadius 指定卡片圓角的弧度,值越大弧度越大
     app:elevation 指定卡片的高度,值越大投影范圍越大,效果越淡-->
<android.support.v7.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:cardCornerRadius="4dp"
    app:elevation="5dp">
    <TextView
        android:id="@+id/info_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</android.support.v7.widget.CardView>

上面代碼在 CardView 中放了一個 TextView,這個 TextView 就會顯示在一張卡片上。


接下來,綜合運(yùn)用第3章的知識,用RecyclerView 來填充項(xiàng)目的主界面部分,實(shí)現(xiàn) OnePiece(海賊王) 列表。

首先,添加如下要用到的依賴庫:

compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.github.bumptech.glide:glide:3.7.0'

上面的 Glide 庫是一個圖片加載庫,其項(xiàng)目主頁地址是:https://github.com/bumptech/glide

接著,在布局文件中添加 RecyclerView,如下:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--******** 第一個子控件 主屏幕顯示 ********-->
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            . . . />
        
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_one_piece"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            . . . />
    </android.support.design.widget.CoordinatorLayout>

    . . .

</android.support.v4.widget.DrawerLayout>

接著,定義一個實(shí)體類 Partner,如下:

public class Partner {

    private String name;  // 伙伴名稱

    private int imageId; // 伙伴對應(yīng)頭像的資源id

    private int profileId; // 人物簡介的資源id

    public Partner(String name, int imageId, int profileId) {
        this.name = name;
        this.imageId = imageId;
        this.profileId = profileId;
    }

    public String getName(){
        return name;
    }

    public int getImageId(){
        return imageId;
    }

    public int getProfileId() {
        return profileId;
    }
}

然后為 RecyclerView 的子項(xiàng)指定一個自定義布局,新建 partner_item.xml,使用 CardView 作為最外層布局,如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    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="wrap_content"
    android:layout_margin="5dp"
    app:cardCornerRadius="4dp">
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        
        <!--******** 顯示頭像********-->
        <ImageView
            android:id="@+id/partner_image"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:scaleType="centerCrop"/>
        
        <!--******** 顯示名稱********-->
        <TextView
            android:id="@+id/partner_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="5dp"
            android:textSize="16sp"/>

    </LinearLayout>

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

接下來為 RecyclerView 準(zhǔn)備一個適配器,新建 PartnerAdapter 類如下:

public class PartnerAdapter extends RecyclerView.Adapter<PartnerAdapter.ViewHolder>{
    
    private Context mContext;
    
    private List<Partner> mPartnerList;
    
    static class ViewHolder extends RecyclerView.ViewHolder{
        CardView cardView;
        ImageView partnerImage;
        TextView partnerName;

        public ViewHolder(View itemView) {
            super(itemView);
            cardView = (CardView) itemView;
            partnerImage = (ImageView) itemView.findViewById(R.id.partner_image);
            partnerName = (TextView) itemView.findViewById(R.id.partner_name);
        }
    }
    
    public PartnerAdapter(List<Partner> partnerList){
        mPartnerList = partnerList;
    }
    
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mContext == null){
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.partner_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Partner partner = mPartnerList.get(position);
        holder.partnerName.setText(partner.getName());
        Glide.with(mContext).load(partner.getImageId()).into(holder.partnerImage);
    }
    
    @Override
    public int getItemCount() {
        return mPartnerList.size();
    }
}

上述代碼中用到 Glide 加載本地圖片,它會幫我們把圖片壓縮,因此不用擔(dān)心內(nèi)存溢出。

適配器準(zhǔn)備好了,最后修改活動中的代碼如下:

public class MaterialDesignActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    private Partner[] partners = {
            new Partner("路飛",R.mipmap.partner_luffy,R.string.partner_luffy),
            new Partner("索隆",R.mipmap.partner_zoro,R.string.partner_zoro),
            new Partner("山治",R.mipmap.partner_sanji,R.string.partner_sanji),
            new Partner("艾斯",R.mipmap.partner_ace,R.string.partner_ace),
            new Partner("羅",R.mipmap.partner_law,R.string.partner_law),
            new Partner("娜美",R.mipmap.partner_nami,R.string.partner_nami),
            new Partner("羅賓",R.mipmap.partner_robin,R.string.partner_robin),
            new Partner("薇薇",R.mipmap.partner_vivi,R.string.partner_vivi),
            new Partner("蕾貝卡",R.mipmap.partner_rebecca,R.string.partner_rebecca),
            new Partner("漢庫克",R.mipmap.partner_hancock,R.string.partner_hancock)};
    
    private List<Partner> partnerList = new ArrayList<>();
    
    private PartnerAdapter adapter;

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

        . . .

        initPartner();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_one_piece);
        GridLayoutManager layoutManager = new GridLayoutManager(this,2);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new PartnerAdapter(partnerList);
        recyclerView.setAdapter(adapter);
    }

    /**
     * 初始化數(shù)據(jù),隨機(jī)挑選50條數(shù)據(jù)
     */
    private void initPartner() {
        partnerList.clear();
        for (int i = 0;i < 50 ;i++){
            Random random = new Random();
            int index = random.nextInt(partners.length);
            partnerList.add(partners[index]);
        }
    }
    . . .
}

現(xiàn)在重新運(yùn)行下程序,效果如下:

卡片式布局效果

可以看到,精美的圖片成功展示出來了,但 Toolbar 卻被擋住了,這是由于 RecyclerView 和 Toolbar 都是放置在 CoordinatorLayout 中,而 CoordinatorLayout 是一個增強(qiáng)版的 FrameLayout,其控件在不進(jìn)行明確定位時默認(rèn)放在布局的左上角,從而產(chǎn)生了遮擋的現(xiàn)象。解決這個 bug 就要借助到另外一個工具了——AppBarLayout。

12.4.2 AppBarLayout

AppBarLayout 是 Design Support 庫提供的一個垂直方向的 LinearLayout,它在內(nèi)部做了很多滾動事件的封裝,并應(yīng)用了一些 Meterial Design 的設(shè)計(jì)理念。

只需兩步就可以解決前面的遮擋問題,第一步是將 Toolbar 嵌套到 AppBarLayout 中,第二步給 RecyclerView 指定一個布局行為。修改布局代碼如下:

<android.support.v4.widget.DrawerLayout
    . . .>

    <!--******** 第一個子控件 主屏幕顯示 ********-->
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
            
        </android.support.design.widget.AppBarLayout>
        
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_one_piece"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

        . . .
    </android.support.design.widget.CoordinatorLayout>

    . . .

</android.support.v4.widget.DrawerLayout>

現(xiàn)在重新運(yùn)行下程序,效果如下:

解決遮擋問題

當(dāng) AppBarLayout 接收到滾動事件時,它內(nèi)部的子控件其實(shí)是可以指定如何取影響這些事件的,下面就來進(jìn)一步優(yōu)化,使當(dāng) RecyclerView 向上滾動時,Toolbar 隱藏,向下滾動時顯示。修改布局代碼如下所示:

<android.support.v4.widget.DrawerLayout
    . . .>

    <!--******** 第一個子控件 主屏幕顯示 ********-->
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_scrollFlags="scroll|enterAlways|snap"/>
            
        </android.support.design.widget.AppBarLayout>
        
        <android.support.v7.widget.RecyclerView
            . . ./>

        . . .
    </android.support.design.widget.CoordinatorLayout>

    . . .

</android.support.v4.widget.DrawerLayout>

在 Toolbar 中添加了一個 **app:layout_scrollFlags **屬性,并指定成 scroll|enterAlways|snap。其中 scroll 指當(dāng) RecyclerView 向上滾動時,Toolbar 會跟著一起向上滾動并隱藏;enterAlways 指向下滾動時一起向下滾動并顯示;snap 指當(dāng) Toolbar 還沒有完全隱藏或顯示時,會根據(jù)當(dāng)前滾動的距離自動選擇隱藏還是顯示。

現(xiàn)在重新運(yùn)行下程序,效果如下:

自動顯示或隱藏 Toolbar

12.5 下拉刷新

在 Meterial Design 中,SwipeRefreshLayout 是用于實(shí)現(xiàn)下拉刷新的核心類,它由 support-v4 庫提供,把要實(shí)現(xiàn)下拉刷新功能的控件放置到 SwipeRefreshLayout 中,就能讓這個控件支持下拉刷新。

SwipeRefreshLayout 用法比較簡單,修改布局,在 RecyclerView 的外面嵌套一層 SwipeRefreshLayout,如下:

<android.support.v4.widget.DrawerLayout
    . . .>

    <!--******** 第一個子控件 主屏幕顯示 ********-->
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

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

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/swipe_refresh"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_one_piece"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
            
        </android.support.v4.widget.SwipeRefreshLayout>
        
        . . .
    </android.support.design.widget.CoordinatorLayout>

    . . .

</android.support.v4.widget.DrawerLayout>

上述代碼值得注意的是,由于 RecyclerView 變成了 SwipeRefreshLayout 的子控件,因此之前用 app:layout_behavior 聲明布局行為要移到 SwipeRefreshLayout 中才行。

接著還要在代碼中處理具體的刷新邏輯,在活動中添加如下代碼:

public class MaterialDesignActivity extends AppCompatActivity {

    . . .
    private SwipeRefreshLayout swipeRefresh;// 刷新

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

        . . .
   
        // 下拉刷新
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);//設(shè)置刷新進(jìn)度條顏色
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 處理刷新邏輯
                refreshPartner();
            }
        });
    }

    /**
     * 下拉刷新數(shù)據(jù)(為簡單起見沒和網(wǎng)絡(luò)交互)
     */
    private void refreshPartner() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initPartner();//重新生成數(shù)據(jù)
                        adapter.notifyDataSetChanged();//通知數(shù)據(jù)變化
                        swipeRefresh.setRefreshing(false);//隱藏刷新進(jìn)度條
                    }
                });
            }
        }).start();
    }

    . . .
}

現(xiàn)在重新運(yùn)行下程序,效果如下:

實(shí)現(xiàn)下拉刷新效果

12.6 可折疊式標(biāo)題欄

作為本章的尾聲,最后來實(shí)現(xiàn)一個震撼的 Material Design 效果——可折疊式標(biāo)題欄。

12.6.1 CollapsingToolbarLayout

CollapsingToolbarLayout 是 Design Support 庫提供的一個作用于 Toolbar 基礎(chǔ)之上的布局,它可讓 Toolbar 的效果變得更加豐富。

不過,CollapsingToolbarLayout 是不能獨(dú)立存在的,只能作為 AppBarLayout 的直接子布局來使用。而 AppBarLayout 又必須是 CoordinatorLayout 的子布局。話不多說,開始吧。

首先創(chuàng)建一個額外的活動 PartnerActivity 來作為海賊的簡介界面,編寫其對應(yīng)的布局文件 activity_partner.xml 如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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">

    <!--******************* 標(biāo)題欄的界面 ****************-->
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="250dp">

        <!-- android:theme 指定主題
        app:contentScrim 指定CollapsingToolbarLayout在趨于折疊以及折疊之后的背景色
        exitUntilCollapsed 指CollapsingToolbarLayout隨著滾動完成折疊后就保留在界面上,不再移出界面-->
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <!-- app:layout_collapseMode 指定當(dāng)前控件在在CollapsingToolbarLayout折疊過程中的折疊模式
             parallax 指折疊過程中會產(chǎn)生一定的錯位偏移
             pin 指在折疊過程中位置始終保持不變-->
            <ImageView
                android:id="@+id/partner_image_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <!--******************* 伙伴的簡介內(nèi)容 ****************-->
    <!--NestedScrollView 在 ScrollView 基礎(chǔ)上增加了嵌套響應(yīng)滾動事件的功能,內(nèi)部只能放一個直接子布局 -->
    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:layout_marginStart="15dp"
                android:layout_marginEnd="15dp"
                android:layout_marginTop="35dp"
                app:cardCornerRadius="4dp">

                <TextView
                    android:id="@+id/partner_profile"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:lineSpacingMultiplier="2"/>

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

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

    <!--******************* 懸浮按鈕 ****************-->
    <!-- app:layout_anchor 指定一個瞄點(diǎn)-->
    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:src="@mipmap/comment"
        app:layout_anchor="@id/appBar"
        app:layout_anchorGravity="bottom|end"/>

</android.support.design.widget.CoordinatorLayout>

編寫完布局 activity_partner.xml 后,開始編寫功能邏輯,修改活動 PartnerActivity 的代碼如下:

public class PartnerActivity extends AppCompatActivity {

    public static final String PARTNER_NAME = "partner_name";  

    public static final String PARTNER_IMAGE_ID = "partner_image_id";
    
    public static final String PARTNER_PROFILE_ID = "partner_profile_id";
    

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

        Intent intent = getIntent();
        String partnerName = intent.getStringExtra(PARTNER_NAME); //海賊名稱
        int partnerImageId = intent.getIntExtra(PARTNER_IMAGE_ID,R.mipmap.partner_luffy);//海賊圖片id
        int partnerProfileId = intent.getIntExtra(PARTNER_PROFILE_ID,R.string.partner_luffy);//海賊資料id

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        ImageView partnerImageView = (ImageView) findViewById(R.id.partner_image_view);
        TextView partnerProfile = (TextView) findViewById(R.id.partner_profile);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        collapsingToolbar.setTitle(partnerName); //設(shè)置標(biāo)題
        Glide.with(this).load(partnerImageId).into(partnerImageView);//設(shè)置圖片
        partnerProfile.setText(getString(partnerProfileId));//設(shè)置內(nèi)容
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                // 返回上一個活動
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

最后,為實(shí)現(xiàn)點(diǎn)擊 RecyclerView 跳轉(zhuǎn)到海賊詳情界面,還需修改適配器 PartnerAdapter 的代碼,添加點(diǎn)擊事件如下:

public class PartnerAdapter extends RecyclerView.Adapter<PartnerAdapter.ViewHolder>{

    . . .

    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        if (mContext == null){
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.partner_item,parent,false);

        final ViewHolder holder = new ViewHolder(view);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Partner partner = mPartnerList.get(position);
                Intent intent = new Intent(mContext,PartnerActivity.class);
                intent.putExtra(PartnerActivity.PARTNER_NAME,partner.getName());
                intent.putExtra(PartnerActivity.PARTNER_IMAGE_ID,partner.getImageId());
                intent.putExtra(PartnerActivity.PARTNER_PROFILE_ID,partner.getProfileId());
                mContext.startActivity(intent);
            }
        });
        return holder;
    }

    . . .
}

好了,現(xiàn)在重新運(yùn)行下程序,效果如下:

海賊詳情展示效果

上面展示的界面雖說已經(jīng)很華麗了,但海賊背景圖片和系統(tǒng)的狀態(tài)欄總感覺有些不搭。下面就進(jìn)一步提升一下。

12.6.2 充分利用系統(tǒng)狀態(tài)欄控件

為改善上面的不搭,接下來將海賊王背景圖和狀態(tài)欄融合到一起。這邊提供兩個方法:

  • 方案 1

借助 android:fitsSystemWindows 這個屬性實(shí)現(xiàn)。將 ImageView 布局結(jié)構(gòu)中的所有父控件都設(shè)置上這個屬性并且指定為 True,修改 activity_partner.xml 如下:

<android.support.design.widget.CoordinatorLayout
    . . .
    android:fitsSystemWindows="true">

    <!--******************* 標(biāo)題欄的界面 ****************-->
    <android.support.design.widget.AppBarLayout
        . . .
        android:fitsSystemWindows="true">

       <android.support.design.widget.CollapsingToolbarLayout
            . . .
            android:fitsSystemWindows="true">

            <ImageView
                android:id="@+id/partner_image_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                android:fitsSystemWindows="true"/>

            . . .

       </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>
   . . .
</android.support.design.widget.CoordinatorLayout>

然后還要在程序的主題中將狀態(tài)欄顏色指定為透明色才行,即在主題中將屬性 **android:statusBarColor **的值指定為 @android:color/transparent 就可以了,但問題是這個屬性在 Android 5.0 系統(tǒng)開始才有的,因此需要準(zhǔn)備兩個同名不同內(nèi)容的主題來實(shí)現(xiàn)。

針對5.0及以上的系統(tǒng),在 res 目錄下創(chuàng)建一個 values-v21 目錄,然后在此目錄創(chuàng)建一個 styles.xml 文件如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="PartnerActivityTheme" parent="AppTheme">
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>

針對5.0以下的系統(tǒng),還需要在 value/styles.xml 文件定義一個同名主題,但內(nèi)容為空,如下:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" 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>
     <!-- 5.0以下使用主題 -->
    <style name="PartnerActivityTheme" parent="AppTheme">
    </style>
</resources>

最后修改 AndroidManifest.xml 中的代碼,讓 PartnerActivity 使用這個主題,如下:

<activity 
    android:name=".chapter12.PartnerActivity"
    android:theme="@style/PartnerActivityTheme">
</activity>

這樣就大功告成了,只要在 5.0 及以上系統(tǒng)運(yùn)行程序,效果如下:

背景圖和狀態(tài)欄融合的效果
  • 方案 2

方案1雖然實(shí)現(xiàn)了融合效果,但在低于5.0的系統(tǒng)上還是不搭,方案2就來稍微改善一下。

方案2也要在 values-v21 目錄下的 styles.xml 中新建一個主題 AppTheme.NoActionBar,如下:

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

在 value/styles.xml 中也新建一個主題 AppTheme.NoActionBar,如下:

<style name="AppTheme.NoActionBar" >
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

接下來修改 AndroidManifest.xml 中的代碼,讓 PartnerActivity 使用這個主題,如下:

 <activity
     android:name=".chapter12.PartnerActivity"
     android:theme="@style/AppTheme.NoActionBar">
 </activity>

最后在 PartnerActivity 中添加如下代碼:

public class PartnerActivity extends AppCompatActivity {
    . . .
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_partner);

        translucentStatusBar();
        . . .
    }

    /**
     * 狀態(tài)欄著色
     */
    private void translucentStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
    }

   . . .
}

現(xiàn)在只要在 4.4 及以上系統(tǒng)運(yùn)行程序就能有如下效果了:

背景圖和狀態(tài)欄融合的效果

好了,本篇文章就介紹到這。代碼傳送門:
??https://github.com/KXwonderful/MyFirstCode

更多關(guān)于 Meterial Design 的內(nèi)容可以參考官方文章:
??https://material.google.com

最后,祝大家新年快樂,雞年吉祥 !

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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