使用过 ToolBar 的朋友肯定对其使用方法不陌生,由于其使用方法非常easy。假设对 ActionBar 使用比較熟练的人来说。ToolBar 就更easy了!只是,相信大家在使用的过程中都遇到过这样一个问题,须要在每个我们要使用的 xml 中加入 ToolBar 这个控件,比方我须要在 MainActivity中使用 ToolBar,则他的 xml 文件须要这样写,

<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.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的代码例如以下

<?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 的关联类

先来看 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"
返回button的图标
app:navigationIcon="?attr/homeAsUpIndicator"
>
</android.support.v7.widget.Toolbar>
</FrameLayout>

ToolBarActivity.java的内容:主要代码是在setContentView(int id) 实现

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 中;

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; /*
* 两个属性
* 1、toolbar是否悬浮在窗体之上
* 2、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 的简单封装就算完毕了。一起来看看封装之后的效果吧

MainActivity.java

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 效果图:

标题居中,右側能够加入button

源代码下载

Android ToolBar 的简单封装的更多相关文章

  1. android RecycleView Adapter简单封装

    早些时候我们使用系统提供个的BaseAdapter的时候为了满足大家的需要,我们总会对BaseAdapter做一层上层的封装,然后对于实际业务我们只需要关心getView里面的View即可,是代码可读 ...

  2. Android AsyncTask 深度理解、简单封装、任务队列分析、自定义线程池

    前言:由于最近在做SDK的功能,需要设计线程池.看了很多资料不知道从何开始着手,突然发现了AsyncTask有对线程池的封装,so,就拿它开刀,本文将从AsyncTask的基本用法,到简单的封装,再到 ...

  3. Android -- OkHttp的简单使用和封装

    1,昨天把okHttp仔细的看了一下,以前都是调用同事封装好了的网络框架,直接使用很容易,但自己封装却不是那么简单,还好,今天就来自我救赎一把,就和大家写写从最基础的OKHttp的简单get.post ...

  4. Android--Retrofit+RxJava的简单封装(三)

    1,继续接着上一篇的讲讲,话说如果像上一篇这样的话,那么我们每一次请求一个结构都要创建一堆的Retrofit对象,而且代码都是相同的,我们可以试试封装一下 先创建一个HttpMethods类,将Ret ...

  5. Google图片加载库Glide的简单封装GlideUtils

    Google图片加载库Glide的简单封装GlideUtils 因为项目里用的Glide的地方比较多,所有简单的封装了以下,其实也没什么,就是写了个工具类,但是还是要把基础说下 Glide的Githu ...

  6. React Native之Fetch简单封装、获取网络状态

    1.Fetch的使用 fetch的使用非常简单,只需传入请求的url fetch('https://facebook.github.io/react-native/movies.json'); 当然是 ...

  7. Android Toolbar中的title居中问题

    版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/167 Android Toolbar中的title居中问题 ...

  8. FMDB简单封装和使用

    工具:火狐浏览器+SQLite Manager插件 ; Xcode; FMDB库; 效果: 项目地址: https://github.com/sven713/PackFMDB 主要参考这两篇博客: 1 ...

  9. okhttp3 get post 简单封装

    最近打算在新项目中使用 okhttp3, 简单封装了一下异步 get post 因为 CallBack 也是在子线程中执行,所以用到了 Handler public class MyOkHttpCli ...

随机推荐

  1. rails 安装后调整gem sources 地址

    rails 安装后调整gem sources 地址 使用https会有认证的问题: 移除原有的: gem sources --remove https://rubygems.org/ 查看当前的: g ...

  2. hdoj 5092 Seam Carving 【树塔DP变形 + 路径输出】 【简单题】

    Seam Carving Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Tot ...

  3. 单机 &amp; 弱联网手游 防破解、金币改动 简单措施

    手游经常使用破解方法 对于一个弱联网或者单机游戏,能够从下面方面去破解: 1.找得到存档文件的,直接破解改动存档文件. 2.找不到存档文件,就在游戏执行时借助一些软件来改动数值,比方用各种改动器手游助 ...

  4. 杭电1018-Big Number(大数)

    Big Number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total ...

  5. ubuntu 使用阿里云 apt 源

    以下内容来自 https://opsx.alibaba.com/mirror Ubuntu对应的“帮助”信息 修改方式:打开 /et/apt/sources.list 将http://archive. ...

  6. 如何解决“因为计算机中丢失php_mbstring.dll”

    配置编译环境时,php.exe报系统错误,无法启动此程序,因为计算机中丢失php_mbstring.dll. 在C:\Windows找到php.ini文件,ctrl+f找到extension=php_ ...

  7. 移动端 | Vue.js对比微信小程序基础语法

    (1)vue 自定义组件与父组件的通信,props:[abb],可以看成自组建的一个自定义属性 (2)vue 模版语法{{}} 只能是在DOM中插入,<div>{{acc}}</di ...

  8. less使用方法总结

    1 变量 我们常常在 CSS 中 看到同一个值重复多次,这样难易于代码维护. 理想状态,应是下面这样: const bgColor="skyblue"; $(".post ...

  9. python爬虫:爬取医药数据库drugbank

    这个是帮朋友做的,难点就是他们有一个反爬虫机制,用request一直不行,后面我就用selenium直接把网页copy下来,然后再来解析本地的html文件,就木有问题啦. 现在看来,写得有点傻,多包涵 ...

  10. Apache2.2伪静态配置

    最近由于工作的需要要配置一下Apache的伪静态化,在网上搜了好多都无法完成,所以觉得有必要在这里写一下. 第一步:打开Apache的httpd.conf文件,把LoadModule rewrite_ ...