前言

 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. Convolutional Networks for Image Semantic Segmentation

    本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/52857657 把前段时间自己整理的一个 ...

  2. Linux删除非空目录的方法

    rmdir 无法删除非空目录. rm -rf 可以递归,强制,删除目录

  3. 硅谷和国内的 iOS 开发到底有何不同?

    前段时间在国内各大互联网公司转了一圈.与各位 iOS 业界大佬交流了之后,深感国内变化之大,敬佩诸位国内开发者的实力和韧劲.除此之外,我还发现硅谷和国内的 iOS 开发还是差别很大,且听我慢慢道来. ...

  4. iOS学习笔记44-Swift(四)枚举和结构体

    一.Swift的枚举 枚举是一系相关联的值定义的一个公共的组类型,同时能够让你在编程的时候在类型安全的情况下去使用这些值.Swift中的枚举比OC中的枚举强大得多, 因为Swift中的枚举是一等类型, ...

  5. XML与DTD简介

    (详细学习参考)https://blog.csdn.net/u013087513/article/details/52745509 XML约束之DTD的使用 (1)为什么要有约束? XML都是用户自定 ...

  6. log4j配置输出到数据库+自定义字段

    Log4j.properties配置 log4j.rootLogger = info,stdout,D,E,A3 log4j.appender.Threshold=info ### 控制台输出### ...

  7. uva 12723 概率dp

    Dudu is a very starving possum. He currently stands in the first shelf of a fridge. This fridge isco ...

  8. DataSet中的表动态设置主键外键的方法

    原文发布时间为:2008-08-01 -- 来源于本人的百度文章 [由搬家工具导入] protected void pk_Click(object sender, EventArgs e)    {  ...

  9. mybatis原理源码大牛连接

    mybatis讲解的非常好的连接: https://www.jianshu.com/nb/5226994 执行流程简介参考:http://www.cnblogs.com/dongying/p/4142 ...

  10. centos 7安装golang1.10

    一.安装&配置 官方下载包(一般需要梯子) https://golang.org/dl/ wget https://dl.google.com/go/go1.10.linux-amd64.ta ...