史上最详细的Toolbar开发讲解,此篇必读!

移动开发 Android
Toolbar 是 android 5.0 引入的一个新控件,Toolbar出现之前,我们很多时候都是使用ActionBar以及ActionActivity实现顶部导航栏的,因此Toolbar可以理解为是ActionBar的升级版。Toolbar大大扩展了ActionBar,使用更灵活,不像ActionBar那么固定,Toolbar更像是一般的View元素,可以被放置在view树体系的任意位置,可以应用动画,可以跟着scrollView滚动,可以与布局中的其他view交互。

Toolbar的简介

Toolbar 是 android 5.0 引入的一个新控件,Toolbar出现之前,我们很多时候都是使用ActionBar以及ActionActivity实现顶部导航栏的,因此Toolbar可以理解为是ActionBar的升级版。Toolbar大大扩展了ActionBar,使用更灵活,不像ActionBar那么固定,Toolbar更像是一般的View元素,可以被放置在view树体系的任意位置,可以应用动画,可以跟着scrollView滚动,可以与布局中的其他view交互。

Toolbar的基本使用

1、要想使用Toolbar,首先应该在Gradle的配置脚本里面添加V7兼容包(代码如下,版本是楠妹妹写本文的时候的版本),或者通过Android Studio的图形化界面的操作方法把V7兼容包依赖进来。

  1. compile 'com.android.support:appcompat-v7:23.1.1' 

2、在我们需要顶部导航栏的布局文件当中添加Toolbar,并且配置一些常用的属性(使用自定义属性的时候需要注意把命名空间“app”添加到根节点)。

  1. xmlns:app="http://schemas.android.com/apk/res-auto" 

这里只列出一些常用的属性,比如最小高度,返回按钮的图标,背景等等。这里需要注意的是,属性值中的“?”表示对Android系统的主题样式进行重用。意思是如果我们改变了主题样式中的colorPrimary属性的话,Toolbar的背景颜色也会随之改变,因此提醒我们去主题样式中进行一些配置。

  1. <android.support.v7.widget.Toolbar 
  2.         android:id="@+id/toolbar" 
  3.         android:layout_width="match_parent" 
  4.         android:layout_height="wrap_content" 
  5.         android:background="?attr/colorPrimary" 
  6.         android:minHeight="?actionBarSize" 
  7.         app:navigationIcon="@mipmap/arrow_left" 
  8.         app:title="标题"/>  

3、在styles.xml文件中进行一些常用的配置。由于我们使用的是

AppCompatActivity,因此必须使用AppCompat的相关主题,笔者这里使用亮色调的没有ActionBar的主题,注意需要在清单文件当中去使用自己定义的主题。为了完全去掉ActionBar,需要把windowActionBar、windowNoTitle以及加上android声明的也写上,确保把系统自带的以及第三方兼容包的ActionBar都彻底去掉。

  1. <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
  2.     <item name="colorPrimary">@color/red</item> 
  3.     <item name="colorPrimaryDark">@color/green</item> 
  4.     <item name="colorAccent">@color/blue</item> 
  5.     <item name="android:textColorPrimary">@color/white</item> 
  6.  
  7.     <item name="android:windowActionBar">false</item> 
  8.     <item name="android:windowNoTitle">true</item> 
  9.  
  10.     <item name="windowActionBar">false</item> 
  11.     <item name="windowNoTitle">true</item> 
  12. </style> 

4、下面对主题中的几个颜色进行讲解,请参考下面的图片进行理解。

  • colorPrimaryDark是我们手机最顶端的状态栏的背景颜色(改变它需要Android5.0以及以上的手机支持才行)。
  • colorPrimary是指导航栏的颜色。
  • colorAccent是指我们常用控件比如Button等的颜色。
  • textColorPrimary是指我们导航栏中标题的颜色。
  • windowBackground是指我们窗体的默认颜色。
  • navigationBarColor是指Android手机中虚拟按键的背景颜色。  

 

5、代码中对Toolbar进行常见的操作。可以通过ID找到Toolbar之后,可以对导航图标进行点击监听,前提必须是在布局文件或者java代码中添加了导航图标。同理也可以使用菜单,具体看注释,不再赘述。

  1. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
  2.  
  3. //对Toolbar左边的导航图标进行监听 
  4. toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
  5. @Override 
  6. public void onClick(View v) { 
  7. Toast.makeText(MainActivity.this, "返回", Toast.LENGTH_SHORT).show(); 
  8. });  
  1. //Toolbar中使用菜单toolbar.inflateMenu(R.menu.menu_main); 
  2. toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {     
  3.     @Override 
  4.     public boolean onMenuItemClick(MenuItem item) {         
  5.         switch (item.getItemId()) {             
  6.             case R.id.action_item1: 
  7.                 Toast.makeText(MainActivity.this, "菜单1", Toast.LENGTH_SHORT).show();                 
  8.                     return true;             
  9.             case R.id.action_item2: 
  10.                 Toast.makeText(MainActivity.this, "菜单2", Toast.LENGTH_SHORT).show();                 
  11.                     return true;             
  12.  
  13.             case R.id.action_item3: 
  14.                 Toast.makeText(MainActivity.this, "菜单3", Toast.LENGTH_SHORT).show();                 
  15.                     return true
  16.         }        return false
  17.  
  18.     } 
  19. }); 

6、运行效果图 

 

Toolbar高级使用篇--自定义Toolbar

通过下面的对比可以知道,原生的Toolbar画面太美不忍直视,一般来说要在项目当中使用Toolbar我们都应该去自定义Toolbar。下面开始讨论如何去自定义Toolbar。  

 

下面先让我给出核心的要点:

  • 自定义布局,添加到Toolbar当中
  • 有必要的时候自定义一些属性
  • 自定义Class继承Toolbar,读取自定义属性,对Toolbar的布局显示,内容进行设置,***需要对外公开一些函数用于设置标题、监听等。下面通过步骤来详细说明。

1、写一个自定义的布局,用来放入自定义Toolbar。

  1. <?xml version="1.0" encoding="utf-8"?> 
  2.  
  3. <RelativeLayout 
  4.     xmlns:android="http://schemas.android.com/apk/res/android" 
  5.     android:layout_width="match_parent" 
  6.     android:layout_height="wrap_content" 
  7.     > 
  8.  
  9.     <RelativeLayout 
  10.         android:layout_width="match_parent" 
  11.         android:layout_height="wrap_content" 
  12.         android:layout_marginLeft="10dp" 
  13.         android:layout_marginRight="10dp"
  14.  
  15.         <ImageView 
  16.             android:id="@+id/toolbar_leftButton" 
  17.             android:layout_width="@dimen/icon_size" 
  18.             android:layout_height="@dimen/icon_size" 
  19.             android:layout_alignParentLeft="true" 
  20.             android:layout_centerVertical="true" 
  21.             android:src="@mipmap/icon_background" 
  22.             android:textColor="@color/white" 
  23.             android:visibility="visible" 
  24.             /> 
  25.  
  26.         <ImageView 
  27.             android:id="@+id/toolbar_rightButton" 
  28.             android:layout_width="@dimen/icon_size" 
  29.             android:layout_height="@dimen/icon_size" 
  30.             android:layout_alignParentRight="true" 
  31.             android:layout_centerVertical="true" 
  32.             android:src="@mipmap/icon_background" 
  33.             android:textColor="@color/white" 
  34.             android:visibility="visible" 
  35.             /> 
  36.  
  37.         <EditText 
  38.             android:id="@+id/toolbar_searchview" 
  39.             style="@style/search_view" 
  40.             android:layout_width="match_parent" 
  41.             android:layout_height="wrap_content" 
  42.             android:layout_centerVertical="true" 
  43.             android:layout_gravity="center" 
  44.             android:layout_marginLeft="10dp" 
  45.             android:layout_marginRight="10dp" 
  46.             android:layout_toLeftOf="@id/toolbar_rightButton" 
  47.             android:layout_toRightOf="@id/toolbar_leftButton" 
  48.             android:drawableLeft="@mipmap/icon_search" 
  49.             android:gravity="center" 
  50.             android:hint="请输入搜索内容" 
  51.             android:visibility="gone" 
  52.             /> 
  53.  
  54.         <TextView 
  55.             android:id="@+id/toolbar_title" 
  56.             android:layout_width="match_parent" 
  57.             android:layout_height="wrap_content" 
  58.             android:layout_centerInParent="true" 
  59.             android:layout_gravity="center" 
  60.             android:layout_marginLeft="10dp" 
  61.             android:layout_marginRight="10dp" 
  62.             android:layout_toLeftOf="@id/toolbar_rightButton" 
  63.             android:layout_toRightOf="@id/toolbar_leftButton" 
  64.             android:gravity="center" 
  65.             android:textColor="@color/white" 
  66.             android:textSize="20sp" 
  67.             android:visibility="gone" 
  68.             /> 
  69.  
  70.     </RelativeLayout> 
  71.  
  72. </RelativeLayout> 

让我们通过下面两张效果图来进行说明吧O(∩_∩)O~~。

由于一般不推荐把宽高意外的属性写在最外面根节点,因此我在最外面的相对布局里面又内嵌了一个相对布局,并且设置了左右的边距(margin)。至于如何布局要根据实际项目而定。楠妹妹这里的需求是,标题和搜索框能够随时切换。因此标题和搜索框是通过项目布局重叠在一起的,需要用到其中一个的时候就把另外一个隐藏掉。另外需要注意的地方就是,左右按钮***也不要用Toolbar自带的,因为可能会造成布局不对称问题,使得标题(搜索框)不能居中。在按钮不使用的时候,我们并不是通过gone的方法隐藏掉的,而是通过@mipmap/icon_background空白图片来进行占位,保持布局对称。   

    

 

2、在values文件夹新建attrs.mxl文件,用于存放自定义的一些属性。这些属性都可以通过字面意思读懂,不详细解释了。

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources>     
  3. <declare-styleable name="CNToolbar"
  4.         <attr name="showSearchView" format="boolean"/> 
  5.         <attr name="leftButtonIcon" format="reference"/> 
  6.         <attr name="rightButtonIcon" format="reference"/> 
  7.         <attr name="myTitle" format="string"/> 
  8.     </declare-styleable> 
  9.  
  10. </resources>  

3、自定义Class继承Toolbar。代码的主要工作是初始化界面还有监听器,对外公开操作的接口。

初始化界面的时候需要把自定义属性的值通过TintTypedArray读取进来,然后进行一些界面显示方面的设置。

初始化监听器,需要用到接口的回调。具体步骤是公开的声明接口,接口里面有onClick方法;声明该接口的实现,作为Toolbar的私有成员变量;公开setListener方法,把传进来的Listener实现类赋值给这个成员变量;在必须的时候调用成员变量的onClick方法(如在左边的按钮的点击事件中调用)。

公开一些函数,比如设置标题,设置是否显示搜索框、标题等等。

  1. /** 
  2.  * 自定义的导航栏 
  3.  */public class CNToolbar extends Toolbar {     
  4.  private TextView toolbar_title;     
  5.  private EditText toolbar_searchview;     
  6.  private ImageView toolbar_leftButton;     
  7.  private ImageView toolbar_rightButton;     
  8.  private View mChildView;     
  9.  private boolean showSearchView;     
  10.  private Drawable left_button_icon;     
  11.  private Drawable right_button_icon;     
  12.  private String title;     
  13.  public CNToolbar(Context context) {         
  14.      this(context, null, 0); 
  15.     }    public CNToolbar(Context context, @Nullable AttributeSet attrs) {         
  16.         this(context, attrs, 0); 
  17.     }    public CNToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {         
  18.         super(context, attrs, defStyleAttr);        //通过代码得到布局文件当中一些属性的值 
  19.         final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, 
  20.                 R.styleable.CNToolbar, defStyleAttr, 0); 
  21.         showSearchView = a.getBoolean(R.styleable.CNToolbar_showSearchView, false); 
  22.         left_button_icon = a.getDrawable(R.styleable.CNToolbar_leftButtonIcon); 
  23.         right_button_icon = a.getDrawable(R.styleable.CNToolbar_rightButtonIcon); 
  24.         title = a.getString(R.styleable.CNToolbar_myTitle); 
  25.         a.recycle();        //初始界面 
  26.         initView();        //初始监听器 
  27.         initListener(); 
  28.     }    /** 
  29.      * 初始化布局 
  30.      */ 
  31.     private void initView() {         
  32.         if (mChildView == null) { 
  33.             mChildView = View.inflate(getContext(), R.layout.toolbar, null); 
  34.  
  35.             toolbar_title = (TextView) mChildView.findViewById(R.id.toolbar_title); 
  36.             toolbar_searchview = (EditText) mChildView.findViewById(R.id.toolbar_searchview); 
  37.             toolbar_leftButton = (ImageView) mChildView.findViewById(R.id.toolbar_leftButton); 
  38.             toolbar_rightButton = (ImageView) mChildView.findViewById(R.id.toolbar_rightButton);             
  39.                 //添加自定义的布局到Toolbar 
  40.             addView(mChildView);            //设置标题、搜索框、左右按钮是否显示,并且设置按钮的图标 
  41.             if (showSearchView) { 
  42.                 showSearchview(); 
  43.                 hideTitle(); 
  44.             } else { 
  45.                 hideSearchview(); 
  46.                 showTitle();                 
  47.                     if (title != null) { 
  48.                     toolbar_title.setText(title); 
  49.                 } 
  50.             }            if (left_button_icon != null) { 
  51.                 toolbar_leftButton.setImageDrawable(left_button_icon); 
  52.             }            if (right_button_icon != null) { 
  53.                 toolbar_rightButton.setImageDrawable(right_button_icon); 
  54.             } 
  55.         } 
  56.  
  57.     }    /** 
  58.      * 重写设置标题的方法 
  59.      * 
  60.      * @param title 
  61.      */ 
  62.     @Override 
  63.     public void setTitle(CharSequence title) { 
  64.         toolbar_title.setText(title); 
  65.     }    @Override 
  66.     public void setTitle(@StringRes int resId) { 
  67.         toolbar_title.setText(resId); 
  68.     }    /** 
  69.      * 设置左右按钮的图标 
  70.      * 
  71.      * @param d 
  72.      */ 
  73.     public void setLeftButtonIconDrawable(Drawable d) { 
  74.         toolbar_leftButton.setImageDrawable(d); 
  75.     }    public void setRightButtonIconDrawable(Drawable d) { 
  76.         toolbar_rightButton.setImageDrawable(d); 
  77.     }    /** 
  78.      * 标题与搜索框的切换 
  79.      */ 
  80.     public void setShowSearchView() { 
  81.         hideTitle(); 
  82.         showSearchview(); 
  83.     }    public void setShowTitleView(String title) { 
  84.         hideSearchview(); 
  85.         showTitle(); 
  86.         toolbar_title.setText(title); 
  87.     }    /** 
  88.      * 左右按钮的监听 
  89.      */ 
  90.     private void initListener() { 
  91.         toolbar_leftButton.setOnClickListener(new OnClickListener() {             
  92.             @Override 
  93.             public void onClick(View v) {                 
  94.                 if (onLeftButtonClickListener != null) { 
  95.                     onLeftButtonClickListener.onClick(); 
  96.                 } 
  97.             } 
  98.         }); 
  99.  
  100.         toolbar_rightButton.setOnClickListener(new OnClickListener() {             
  101.             @Override 
  102.             public void onClick(View v) {                 
  103.                 if (onRightButtonClickListener != null) { 
  104.                     onRightButtonClickListener.onClick(); 
  105.                 } 
  106.             } 
  107.         }); 
  108.     }    public interface OnLeftButtonClickListener {         
  109.         void onClick(); 
  110.     }    public interface OnRightButtonClickListener {         
  111.         void onClick(); 
  112.  
  113.     }    private OnLeftButtonClickListener onLeftButtonClickListener;     
  114.         private OnRightButtonClickListener onRightButtonClickListener;     
  115.         public void setOnLeftButtonClickListener(OnLeftButtonClickListener listener) { 
  116.         onLeftButtonClickListener = listener; 
  117.     }    public void setOnRightButtonClickListener(OnRightButtonClickListener listener) { 
  118.         onRightButtonClickListener = listener; 
  119.     }    /** 
  120.      * 设置标题或者搜索框是否显示 
  121.      */ 
  122.     private void showTitle() { 
  123.         toolbar_title.setVisibility(View.VISIBLE); 
  124.     }    private void hideTitle() { 
  125.         toolbar_title.setVisibility(View.GONE); 
  126.     }    private void showSearchview() { 
  127.         toolbar_searchview.setVisibility(View.VISIBLE); 
  128.     }    private void hideSearchview() { 
  129.         toolbar_searchview.setVisibility(View.GONE); 
  130.     } 
  131.  
  132.         4、使用,在必须的地方如同一般的控件去使用就可以了,注意加上自定义属性的命名空间,一般为auto就可以了。 
  133.  
  134. <?xml version="1.0" encoding="utf-8"?> 
  135.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  136.               xmlns:app="http://schemas.android.com/apk/res-auto" 
  137.               android:layout_width="match_parent" 
  138.               android:layout_height="match_parent" 
  139.               android:orientation="vertical"
  140.  
  141.     <com.nan.cnshop.widget.CNToolbar 
  142.         android:id="@+id/toolbar" 
  143.         android:layout_width="match_parent" 
  144.         android:layout_height="wrap_content" 
  145.         android:background="?attr/colorPrimary" 
  146.         android:minHeight="?actionBarSize" 
  147.         app:leftButtonIcon="@mipmap/icon_back_32px" 
  148.         app:showSearchView="false" 
  149.         app:myTitle="首页" 
  150.         /> 
  151.  
  152.     <WebView 
  153.         android:id="@+id/webview" 
  154.         android:layout_width="match_parent" 
  155.         android:layout_height="match_parent" 
  156.         /> 
  157.        </LinearLayout> 

4、使用,在必须的地方如同一般的控件去使用就可以了,注意加上自定义属性的命名空间,一般为auto就可以了。

  1. <?xml version="1.0" encoding="utf-8"?> 
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.               xmlns:app="http://schemas.android.com/apk/res-auto" 
  4.               android:layout_width="match_parent" 
  5.               android:layout_height="match_parent" 
  6.               android:orientation="vertical"
  7.  
  8.     <com.nan.cnshop.widget.CNToolbar 
  9.         android:id="@+id/toolbar" 
  10.         android:layout_width="match_parent" 
  11.         android:layout_height="wrap_content" 
  12.         android:background="?attr/colorPrimary" 
  13.         android:minHeight="?actionBarSize" 
  14.         app:leftButtonIcon="@mipmap/icon_back_32px" 
  15.         app:showSearchView="false" 
  16.         app:myTitle="首页" 
  17.         /> 
  18.  
  19.     <WebView 
  20.         android:id="@+id/webview" 
  21.         android:layout_width="match_parent" 
  22.         android:layout_height="match_parent" 
  23.         /> 
  24.        </LinearLayout> 

代码当中也可以使用了,具体就不再赘述了。

  1. final CNToolbar toolbar = (CNToolbar) v.findViewById(R.id.toolbar); 
  2.  
  3. toolbar.setOnLeftButtonClickListener(new CNToolbar.OnLeftButtonClickListener() {     
  4.     @Override 
  5.     public void onClick() { 
  6.         toolbar.setShowSearchView(); 
  7.     } 
  8. }); 
责任编辑:庞桂玉 来源: 安卓巴士Android开发者门户
相关推荐

2010-08-26 10:28:43

2024-01-09 12:06:55

MVCC并发控制MySQL

2015-05-19 11:11:29

JavaScript事件使用指南

2016-12-22 19:53:46

AndroidAPPReactNative

2023-11-30 08:32:31

OpenFeign工具

2013-08-05 11:34:02

2012-10-31 09:16:36

IT管理

2014-04-09 09:55:12

2012-12-25 09:53:40

域名

2009-10-10 13:56:44

IIS应用程序VB开发

2012-10-18 18:40:24

2011-01-20 17:59:53

网络安全路由配置路由安全

2011-08-29 09:19:25

c语言

2015-07-23 09:40:24

烂代码程序员

2020-04-09 11:23:30

微软域名僵尸网络

2014-04-23 16:31:42

Windows背景音乐

2013-08-26 11:08:55

产品经理移动开发

2013-08-26 11:09:10

产品经理产品

2015-12-21 11:51:43

JavaScript开发者调查

2024-02-07 08:22:36

点赞
收藏

51CTO技术栈公众号