前言

 android5.X新增的一个控件Toolbar,这个控件比ActionBar更加自由,可控,因为曾经的ActionBar的灵活性比較差,所以google逐渐使用Toolbar替代ActionBar,所以Toolbar也能够说是超级ActionBar。

这篇文章不具体介绍ToolBar的使用(定制),主要是介绍Toolbar使用的一个样例。即Toolbar结合DrawerLayout实现抽屉菜单。

使用这个两个控件须要引入对应的库依赖:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
}

1. Toolbar的布局文件

include_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="? attr/actionBarSize"
android:background="?attr/colorPrimary"> </android.support.v7.widget.Toolbar>

Toolbar控件使用和其它的控件使用相似,须要注意的是引用v7扩展包中的Toolbar,而不是系统自带的那个Toolbar。这样能够兼容v21以下的设备。

2. 加入动作菜单

菜单项通常放在menu目录下的一个xml文件里

menu_main.xml

<menu 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"
tools:context="com.example.lt.toolbar.MainActivity">
<item
android:id="@+id/ab_search"
android:orderInCategory="80"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="@string/action_search"
app:showAsAction="ifRoom"/> <item
android:id="@+id/action_share"
android:orderInCategory="90"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
android:title="@string/action_settings"
app:showAsAction="ifRoom"/> <item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never"/>
</menu>

之前的ActionBar也是须要使用这个菜单文件来渲染其动作菜单,Toolbar也一样。

有了菜单布局文件。还须要在代码中初始化菜单,这样Toolbar上面才会显示这些动作菜单(重写Activity的onCreateOptionsMenu()方法):

/**
* 必须重写该方法创建菜单。不然菜单不会显示在Toolbar中
* @param menu
* @return
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}

3. activity主布局文件

activity_main.xml

<?

xml version="1.0" encoding="utf-8"?

>
<LinearLayout
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:orientation="vertical"
android:layout_height="match_parent"
> <include layout="@layout/include_toolbar"></include> <android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:id="@+id/drawerLayout"
android:layout_weight="1"
android:layout_height="0dp"> <!-- 内容界面 -->
<FrameLayout
android:layout_width="match_parent"
android:id="@+id/fl_containor"
android:layout_height="match_parent"> </FrameLayout> <!-- 菜单界面。必须指定水平重力 -->
<LinearLayout
android:layout_width="200dp"
android:layout_gravity="start"
android:orientation="vertical"
android:background="#fff"
android:layout_height="match_parent">
<ListView
android:id="@+id/lv_menu"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="wrap_content"> </ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout> </LinearLayout>

4. 代码初始化Toolbar

 @NonNull
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setLogo(R.mipmap.ic_launcher);
mToolbar.setTitle("主标题");
mToolbar.setSubtitle("副标题");
// ...
// 这种方法非常重要,不能少,让toolbar代替ActionBar
setSupportActionBar(mToolbar);
}

注意:一定要调用setSupportActionBar()让Toolbar代替ActionBar,同一时候还须要将当前Activity的主题设置为NoActionBar。

<!-- 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. 将Toolbar与DrawerLayout状态绑定

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.close);
drawerToggle.syncState();
mDrawerLayout.setDrawerListener(drawerToggle);

6. 初始化内容视图

private void initContentView() {
Fragment fragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putString("title","首页");
fragment.setArguments(bundle);
mFm.beginTransaction().replace(R.id.fl_containor,fragment).commit();
}

ContentFragment.java

package com.example.lt.toolbar;

import android.app.ActionBar;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; /**
* Created by lt on 2016/3/16.
*/
public class ContentFragment extends Fragment{ @Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
TextView textView = new TextView(getActivity());
if(getArguments()!=null){
String title = getArguments().getString("title");
textView.setText(title);
textView.setGravity(Gravity.CENTER);
textView.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
}
return textView;
}
}

7. 初始化抽屉菜单

private void initLeftMenu() {
ListView menuList = (ListView) findViewById(R.id.lv_menu);
menuList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1
, new String[]{"首页","新闻","个人中心"}));
menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<? > parent, View view, int position, long id) {
Fragment fragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putString("title", ((TextView) view).getText().toString());
fragment.setArguments(bundle);
mFm.beginTransaction().replace(R.id.fl_containor, fragment).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
});
}

这里用了一个ListView来渲染抽屉菜单,并设置了当点击后替换右边的内容视图的点击事件。

完整代码:

package com.example.lt.toolbar;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.Gravity;
import android.view.MenuInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends AppCompatActivity { private FragmentManager mFm;
private DrawerLayout mDrawerLayout;
private Toolbar mToolbar; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFm = getSupportFragmentManager();
setContentView(R.layout.activity_main); initToolbar(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.close);
drawerToggle.syncState();
mDrawerLayout.setDrawerListener(drawerToggle); initLeftMenu();
initContentView();
} @NonNull
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setLogo(R.mipmap.ic_launcher);
mToolbar.setTitle("主标题");
mToolbar.setSubtitle("副标题");
// 这种方法非常重要。不能少,让toolbar代替ActionBar
setSupportActionBar(mToolbar);
} private void initContentView() {
Fragment fragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putString("title","首页");
fragment.setArguments(bundle);
mFm.beginTransaction().replace(R.id.fl_containor,fragment).commit();
} private void initLeftMenu() {
ListView menuList = (ListView) findViewById(R.id.lv_menu);
menuList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1
, new String[]{"首页","新闻","个人中心"}));
menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putString("title", ((TextView) view).getText().toString());
fragment.setArguments(bundle);
mFm.beginTransaction().replace(R.id.fl_containor, fragment).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
});
} /**
* 必须重写该方法创建菜单,不然菜单不会显示在Toolbar中
* @param menu
* @return
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
}

执行效果演示:

这篇文章就介绍了Toolbar+DrawerLayout实现带有动画效果的常见的一种抽屉菜单。Toolbar很多其它具体的的使用方法及样式定制能够參考官方文档,也能够參考以下这篇文章。我个人认为介绍得比較具体。

Toolbar具体介绍:android:ToolBar具体解释(手把手教程)

文章Demo下载:http://download.csdn.net/detail/ydxlt/9464817

android 5.X Toolbar+DrawerLayout实现抽屉菜单的更多相关文章

  1. wemall doraemon中Android app商城系统解决左侧抽屉菜单和viewpager不能兼容问题

    完美解决左侧抽屉菜单和viewpager不能兼容左右滑动的问题,可进行参考. WeMall-Client/res/layout/wemall_main_ui.xml </RadioGroup&g ...

  2. 可折叠的ToolBar+抽屉菜单NavigationView+浮动按钮FloatButton

    使用Material Design风格的ToolBar和抽屉导航 先看个简单的运行效果 主要记录下布局的写法 1 用到的Google Design依赖和V7包依赖 compile 'com.andro ...

  3. Android——使用Toolbar + DrawerLayout快速实现高大上菜单侧滑(转)

    今天就来使用官方支持库来快速实现这类效果,需要使用到Toolbar和DrawerLayout,详细步骤如下:(如果你还不知道这两个Widget,先自己Google吧~) 1.首先需要添加appcomp ...

  4. Android使用ToolBar+DrawerLayout+NavigationView实现侧滑抽屉效果

    学会使用DrawerLayout 学会使用NavigationView 学会使用ToolBar+DrawerLayout+NavigationView实现侧滑抽屉效果 学会实现Toolbar在顶部以及 ...

  5. android组件之DrawerLayout(抽屉导航)-- 侧滑菜单效果

    转载请注明出处:http://blog.csdn.net/crazy1235/article/details/41696291 一. 介绍     导航抽屉显示在屏幕的最左侧,默认情况下是隐藏的,当用 ...

  6. Android抽屉菜单DrawerLayout的实现案例

    (1)项目布局文件 activity_main.xml <android.support.v4.widget.DrawerLayout xmlns:android="http://sc ...

  7. Android DrawerLayout Plus 增强版抽屉菜单

    DrawerLayout是官方提供的侧滑菜单,相比SliddingMenu,它更加轻量级.默认情况下,DrawerLayout可以设置左侧或者右侧滑出菜单.如下,   xml布局: <!-- & ...

  8. android提供ToolBar实现划动菜单的陷阱

    代码如下: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android: ...

  9. Android Design Support Library(二)用NavigationView实现抽屉菜单界面

    NavigationView在MD设计中非常重要,之前Google也提出了使用DrawerLayout来实现导航抽屉.这次,在Android Design Support Library中,Googl ...

随机推荐

  1. CM10 WIFI连不上解决方案

    手机是Moto Mileston2 ,好久之前就刷成了CM10, 但是一直没出问题. 最近,发现在某些路由器上连接不上,总是 在验证账户或者获取IP. 解决办法如下: http://moto.zol. ...

  2. springboot添加外部jar包及打包

    项目中除了从pom中添加依赖包,还可以添加本地的jar包,怎么做呢? 1.在src下新建目录lib,将jar包添加到lib中 2.在pom文件里添加配置以下属性,就可以使用jar包了 <depe ...

  3. 九度oj 题目1374:所有员工年龄排序

    题目描述: 公司现在要对所有员工的年龄进行排序,因为公司员工的人数非常多,所以要求排序算法的效率要非常高,你能写出这样的程序吗? 输入: 输入可能包含多个测试样例,对于每个测试案例, 输入的第一行为一 ...

  4. formData使用总结

    1.formData基本使用 //可以从form元素初始化一个FormData对象,或者new一个空对象 var formData = new FormData([fromElement]); //可 ...

  5. 关于pymongo的一些说明

    问题 一: 在pymongo中使用find是得到1个游标对象的,如果你想实现MongoDB shell中find操作,例如: > db.test.find() { "_id" ...

  6. bootstrap 事件shown.bs.modal用于监听并执行你自己的代码【写hostmanger关联部门遇到的问题及解决方法】

    背景:记录写hostmanger中用户下拉框关联部门遇到的问题及解决方法 问题:需求是展示页面展示用户所属的部门,点击修改按钮后,弹出对应的model,这个时候部门的select要默认选中用户所在的s ...

  7. 古代猪文 BZOJ 1951

    古代猪文 [问题描述] “在那山的那边海的那边有一群小肥猪.他们活泼又聪明,他们调皮又灵敏.他们自由自在生活在那绿色的大草坪,他们善良勇敢相互都关心……” ——选自猪王国民歌 很久很久以前,在山的那边 ...

  8. jmeter登录禅道案例

    下载jmeter,配置环境变量 变量名:JMETER_HOME 变量值:C:\Program Files\apache-jmeter-2.11 变量名:CLASSPATH 变量值:%JMETER_HO ...

  9. py2exe多文件转换

    # -*- coding: utf-8 -*- #import distutils #import py2exe #from distutils.core import setup #distutil ...

  10. LeetCode OJ--Unique Paths II **

    https://oj.leetcode.com/problems/unique-paths-ii/ 图的深搜,有障碍物,有的路径不通. 刚开始想的时候用组合数算,但是公式没有推导出来. 于是用了深搜, ...