Android ToolBar 的簡單封裝

使用過 ToolBar 的朋友確定對其使用方法不陌生,由於其用法很簡單,若是對 ActionBar 使用比較熟練的人來講,ToolBar 就更容易了!不過,相信你們在使用的過程當中都遇到過這樣一個問題,須要在每個咱們要使用的 xml 中添加 ToolBar 這個控件,好比我須要在 MainActivity中使用 ToolBar,則他的 xml 文件須要這樣寫,java

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <android.support.v7.widget.Toolbar
        android:layout_height="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:id="@+id/id_tool_bar"
        android:background="?attr/colorPrimary"
        app:navigationIcon="?attr/homeAsUpIndicator"
        >
    </android.support.v7.widget.Toolbar>
    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdfasf"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

同理其餘 Activity 中須要用頁都須要在 xml添加android

<android.support.v7.widget.Toolbar
        android:layout_height="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:id="@+id/id_tool_bar"
        android:background="?attr/colorPrimary"
        app:navigationIcon="?attr/homeAsUpIndicator"
        >
 </android.support.v7.widget.Toolbar>

這樣一段代碼,雖然很少,可是咱們最煩的就是寫重複代碼,也不符合咱們的編程思想;因此就有了如下寫法編程

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <include layout="@layout/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        />
    <TextView        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdfasf"
        android:layout_alignParentBottom="true"/></RelativeLayout>

toolbar.xml的代碼以下app

<?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:layout_height="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:id="@+id/id_tool_bar"
        android:background="?attr/colorPrimary"
        app:navigationIcon="?attr/homeAsUpIndicator"
        >
    </android.support.v7.widget.Toolbar></FrameLayout>

這樣咱們只須要在每一個咱們要使用 toolbar 的 xml 中經過 include 嵌入 toolbar.xml佈局就行,感受和以前的比,確實是少了幾行代碼!可是意義不大。而我這裏要實現的封裝,是能夠不須要在 xml 中寫一行關於 toolbar 的代碼,也就是跟平時不用 toolbar 同樣的寫法便可!請接着往下看。 
前提是準備好toolbar.xml,ToolBarActivity.java,ToolBarHelper.java 
toolbar.xml中配置 toolbar 的基本屬性: 
toolbar 的寬高,toolbar 的背景顏色等其餘樣式 
ToolBarActivity.java是因此須要使用 toolbar Activity 的父類,這裏我把他定義爲抽象類,由於單獨的這個類不能完成任何功能 
ToolBarHelper.java 是 Activity 和 toolbar 的關聯類ide

先來看 toolbar.xml的代碼佈局

<?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        設置高度爲 ActionBar 的高度        android:layout_height="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:id="@+id/id_tool_bar"
        背景顏色爲 ActionBar 的背景顏色        android:background="?attr/colorPrimary"
        返回按鈕的圖標        app:navigationIcon="?attr/homeAsUpIndicator"
        >
    </android.support.v7.widget.Toolbar></FrameLayout>

ToolBarActivity.java的內容:主要代碼是在setContentView(int id) 實現this

package toolbar.toolbar;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.MenuItem;/**
 * Created by moon.zhong on 2015/6/12.
 * time : 10:26
 */public abstract class ToolBarActivity extends AppCompatActivity {
    private ToolBarHelper mToolBarHelper ;    public Toolbar toolbar ;    @Override
    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
    }    @Override
    public void setContentView(int layoutResID) {

        mToolBarHelper = new ToolBarHelper(this,layoutResID) ;
        toolbar = mToolBarHelper.getToolBar() ;
        setContentView(mToolBarHelper.getContentView());        /*把 toolbar 設置到Activity 中*/
        setSupportActionBar(toolbar);        /*自定義的一些操做*/
        onCreateCustomToolBar(toolbar) ;
    }    public void onCreateCustomToolBar(Toolbar toolbar){
        toolbar.setContentInsetsRelative(0,0);
    }    @Override
    public boolean onOptionsItemSelected(MenuItem item) {        if (item.getItemId() == android.R.id.home){
            finish();            return true ;
        }        return super.onOptionsItemSelected(item);
    }
}

ToolBarHelper.java 
這個類的功能是:先建立一個 ViewGroup 來做爲視圖的父 View,把用戶定義的 View,和 toolBar 依次 Add 到 ViewGroup 中;spa

package toolbar.toolbar;import android.content.Context;import android.content.res.TypedArray;import android.support.v7.widget.Toolbar;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.FrameLayout;/**
 * Created by moon.zhong on 2015/6/12.
 * time : 10:45
 */public class ToolBarHelper {

    /*上下文,建立view的時候須要用到*/
    private Context mContext;    /*base view*/
    private FrameLayout mContentView;    /*用戶定義的view*/
    private View mUserView;    /*toolbar*/
    private Toolbar mToolBar;    /*視圖構造器*/
    private LayoutInflater mInflater;    /*
    * 兩個屬性
    * 一、toolbar是否懸浮在窗口之上
    * 二、toolbar的高度獲取
    * */
    private static int[] ATTRS = {
            R.attr.windowActionBarOverlay,
            R.attr.actionBarSize
    };    public ToolBarHelper(Context context, int layoutId) {        this.mContext = context;
        mInflater = LayoutInflater.from(mContext);        /*初始化整個內容*/
        initContentView();        /*初始化用戶定義的佈局*/
        initUserView(layoutId);        /*初始化toolbar*/
        initToolBar();
    }    private void initContentView() {        /*直接建立一個幀佈局,做爲視圖容器的父容器*/
        mContentView = new FrameLayout(mContext);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mContentView.setLayoutParams(params);

    }    private void initToolBar() {        /*經過inflater獲取toolbar的佈局文件*/
        View toolbar = mInflater.inflate(R.layout.toolbar, mContentView);
        mToolBar = (Toolbar) toolbar.findViewById(R.id.id_tool_bar);
    }    private void initUserView(int id) {
        mUserView = mInflater.inflate(id, null);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        TypedArray typedArray = mContext.getTheme().obtainStyledAttributes(ATTRS);        /*獲取主題中定義的懸浮標誌*/
        boolean overly = typedArray.getBoolean(0, false);        /*獲取主題中定義的toolbar的高度*/
        int toolBarSize = (int) typedArray.getDimension(1,(int) mContext.getResources().getDimension(R.dimen.abc_action_bar_default_height_material));
        typedArray.recycle();        /*若是是懸浮狀態,則不須要設置間距*/
        params.topMargin = overly ? 0 : toolBarSize;
        mContentView.addView(mUserView, params);

    }    public FrameLayout getContentView() {        return mContentView;
    }    public Toolbar getToolBar() {        return mToolBar;
    }
}

到這裏,toolbar 的簡單封裝就算完成了,一塊兒來看看封裝以後的效果吧code

MainActivity.javaorm

package toolbar.toolbar;import android.os.Bundle;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;public class MainActivity extends ToolBarActivity {

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

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

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">
    <TextView        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdfasf"
        android:layout_alignParentBottom="true"/></RelativeLayout>

到這裏咱們無論是 MainActivity 仍是 activity_main中都沒有出現 ToolBar,只是 MainActivity 再也不繼承 AppCompatActivity,而是繼承咱們 ToolBarActivity,運行效果看看: 

ToolBar 的其餘用法這裏就不講了,跟 ActionBar 用法幾乎同樣,

最後: 
在使用 ToolBar 的時候,須要使用無 ActionBar 的主題,

    <!-- Base application theme. -->
    <style name="AppThemeParent" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@android:color/holo_red_light</item>

    </style>

再上一張自定義 View 的 ToolBar 效果圖: 
標題居中,右側能夠添加按鈕 

源碼下載

相關文章
相關標籤/搜索