[Android] 在Android5.0下的帶有DrawerLayout的工程模板

下面用的例子代碼來源于 Android Studio 的工程模板,只是對(duì)里面的一些設(shè)計(jì)進(jìn)行記錄,吸取下谷歌的精華(污)。

我們先看看是什么樣子的

QQ截圖20160116105454.png

QQ截圖20160116105504.png

XML布局文件


先從 XML 文件說起,一共是 4 個(gè)布局文件:
activity_main.xml -- 根布局
app_bar_main.xml -- appbar
content_main.xml --主內(nèi)容布局
nav_header_main.xml -- 側(cè)邊欄布局

我們看看 activity_main.xml 中的代碼:

<?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"    
  xmlns:tools="http://schemas.android.com/tools"    
  android:id="@+id/drawer_layout"   
  android:layout_width="match_parent"
  android:layout_height="match_parent" 
  android:fitsSystemWindows="true"
  tools:openDrawer="start">  

  <include       
      layout="@layout/app_bar_main"        
      android:layout_width="match_parent"        
      android:layout_height="match_parent" />    


  <android.support.design.widget.NavigationView        
      android:id="@+id/nav_view"        
      android:layout_width="wrap_content"        
      android:layout_height="match_parent"        
      android:layout_gravity="start"       
      android:fitsSystemWindows="true"        
      app:headerLayout="@layout/nav_header_main"     
      app:menu="@menu/activity_main_drawer" />

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

可以看到根布局是由一個(gè) DrawerLayout 包裹住的,因?yàn)橐褂?DrawerLayout 就要把他放在最外層,在 DrawerLayout 里面,第一個(gè)是主內(nèi)容布局,直接展示到 activity 。第二個(gè)是側(cè)邊欄 NavigationView,通過設(shè)置側(cè)邊欄的 app:menu 屬性可以定義側(cè)邊欄的菜單項(xiàng), app:headerLayout 屬性可以定義側(cè)邊欄的頂部樣式(也可以沒有頂部樣式,那樣就是一個(gè)菜單盒子了),我們看看關(guān)于headerlayout是怎么編寫的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>

可以看到里面其實(shí)跟普通布局并沒什么區(qū)別,使用了一個(gè) imageview 和兩個(gè) textview 組成 效果圖如下:

QQ截圖20160116105823.png

我們繼續(xù)看上面的activity_main文件,其中第一個(gè)主內(nèi)容布局使用了 include 導(dǎo)入了 app_bar_main 。我們跟進(jìn)去看一下:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.shire.forumdemo2.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

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

    <include layout="@layout/content_main" />

    <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="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

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

可以看到 里面是一個(gè) CoordinatorLayout 作為最外層的包裹,這樣的好處是可以讓 appbar 和下面的 fab 能夠產(chǎn)生一個(gè)動(dòng)畫效果,詳細(xì)的 CoordinatorLayout 用法可以參考:

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0717/3196.html

在這個(gè)文件中,最上面是 appbar ,中間是一個(gè)導(dǎo)入文件 content_main 最下面是一個(gè) fab 。這就構(gòu)成了我們的主布局文件,其中因?yàn)?appbar 和 fab 相對(duì)獨(dú)立,所以單獨(dú)寫出來。詳細(xì)的內(nèi)容布局通過 content_main 文件來進(jìn)行編寫。里面內(nèi)容很簡(jiǎn)單 ,就是一個(gè) layout 一個(gè) textview 就不展示了。

總結(jié)一下,關(guān)于布局文件的設(shè)計(jì)。谷歌的建議的是:DrawerLayout>CoordinatorLayout>content_main

最外層使用 DrawerLayout,主布局使用 include 方式插入。插入的主布局使用 CoordinatorLayout 包裹,實(shí)現(xiàn)動(dòng)畫效果,然后將 appbar 和 fab 單獨(dú)提出編寫,詳細(xì)布局繼續(xù)使用 include 方式插入 content_main 文件。

XML樣式文件


看完了布局文件我們來看樣式文件:
默認(rèn)會(huì)創(chuàng)建兩個(gè):
styles.xml
styles.xml-v21

先看第一個(gè)styles.xml

<resources>

    <!-- Base application theme. -->
    <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>

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

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

我們來慢慢看各個(gè)屬性:

colorPrimary = appbar顏色
colorPrimaryDark = 狀態(tài)欄顏色
colorAccent = 強(qiáng)調(diào)色

windowActionBar = 是否啟用actionbar,因?yàn)槲覀兪褂昧藅oolbar作為appbar所以不需要actionbar了
windowNoTitle = 去除標(biāo)題欄(我猜的,錯(cuò)誤請(qǐng)指正),去掉去掉 我們有toolbar了

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
至于這個(gè),是一個(gè)黑色主題,用于appbar的,這樣上面的字體才能是白色顯示。

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
這個(gè)的話,是因?yàn)槭褂昧撕谏黝}的時(shí)候,雖然我們可以自定義appbar的背景色,當(dāng)時(shí)在我們進(jìn)行點(diǎn)擊
menu的時(shí)候彈出來的背景色還是黑色。。。。這個(gè)不好看的 通常menu我們使用白底黑字,所以這個(gè)主題是給彈出菜單用的。至于設(shè)置方式,回顧下上面的appbar部分:

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"> //這是設(shè)置appbar整體樣式為dark樣式

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" /> //這是設(shè)置彈出菜單為light樣式

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

代碼


通過以上,我們就算是看完了樣式文件,接下來看看代碼中的實(shí)現(xiàn):

package com.shire.forumdemo2;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

//繼承了AppCompatActivity而不是ActionBarActivity
//還添加了NavigationView.OnNavigationItemSelectedListener接口,這是用于監(jiān)聽側(cè)邊欄菜單被點(diǎn)擊的事件
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

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

        //findID沒啥好說的
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //這個(gè)方法是設(shè)置我們的toolbar作為appbar  不設(shè)置的話只相當(dāng)于一個(gè)普通view,一些appbar的特性是支持不了的!
        setSupportActionBar(toolbar);

        //findID沒啥好說的    
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        //設(shè)置fab的點(diǎn)擊事件監(jiān)聽,其實(shí)和按鈕都一個(gè)樣
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        
        //findID沒啥好說的    
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        //這個(gè)類可以方便的將 DrawerLayout,appbar綁定在一起,自動(dòng)添加一個(gè)漢堡按鈕,并且打開關(guān)閉時(shí)帶有動(dòng)畫顯示
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        //設(shè)置監(jiān)聽器為toggle
        drawer.setDrawerListener(toggle);
        //啟動(dòng)綁定!
        toggle.syncState();
      
        //findID沒啥好說的    
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        //菜單項(xiàng)監(jiān)聽器。。看下面吧
        navigationView.setNavigationItemSelectedListener(this);
    }

    //這里捕獲了一個(gè)返回操作,在按下返回鍵的時(shí)候先看DrawerLayout有木有打開,如果打開了先關(guān)閉DrawerLayout ,如果沒打開 才執(zhí)行返回操作,不過這里也有一個(gè)fingid我也是醉了= =
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

     //appbar菜單項(xiàng) 沒啥好說的 都知道吧

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


     //側(cè)邊菜單的點(diǎn)擊事件
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        //看看是誰點(diǎn)擊的  話說為啥不用switch  = =
        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        //這里又FindID了。。。警察叔叔抓住他
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        //響應(yīng)完時(shí)間之后就關(guān)掉自己咯~
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

以上,就是谷歌推出的默認(rèn)模板,如果你正好需要使用DrawerLayout,并且頁面不復(fù)雜,推薦使用這個(gè)快速開發(fā)。

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

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