Google 官方 侧滑 drawerlayout
一.概述
目前侧滑框架已经很多了,但是我常用的也就那么2个 ,slidingmenu 和sidemenu-android, 但是项目要求使用官方的,所以就看了一下drawerlayout
二.代码
官方代码还是很好理解的,之前也用过,但是真实项目没使用过 ,代码如下
package com.kun.drawer_layout; import java.util.Locale; import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast; public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mTitle = mDrawerTitle = getTitle();
//侧边栏 item 名称
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
//侧边栏容器对象
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//侧边栏 Listview
mDrawerList = (ListView) findViewById(R.id.left_drawer); //设置侧滑阴影,
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//设置侧滑 adapter ,并添加点击事件
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); //设置左上角 actionbar 图标可见
getActionBar().setDisplayHomeAsUpEnabled(true);
//需要api level 14 使用home-icon 可点击
getActionBar().setHomeButtonEnabled(true); //actionbar 抽屉开关
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
//侧滑关闭
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);//设置侧滑item名字到 actionbar上面
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
//侧滑打开
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) {
selectItem(0);
}
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
} /* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
} /* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
} //显示侧滑item --内容区域
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args); FragmentManager fragmentManager = getFragmentManager();
//让fragment替换 帧布局内容
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); //更新选中的 item ,并关闭抽屉
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} @Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
} /**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/ @Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
} @Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
} /**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number"; public PlanetFragment() {
// Empty constructor required for fragment subclasses
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i]; int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
用到的几个布局如下
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"> <!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/> <!--
android:choiceMode 选中状态 跟itemclick没有冲突
none 值为0,表示无选择模式;
singleChoice 值为1,表示最多可以有一项被选中;
multipleChoice 值为2,表示可以多项被选中。 android:layout_gravity left或right left或start right或end
表示在抽屉里的效果是从左到右还是从右到左出现
-->
</android.support.v4.widget.DrawerLayout>
侧滑列表很简单,就是一个Listview装载了 TextView , 侧滑item对应的是fragment, 而fragment 布局更简单只是 一个图片
最后来张图

Google 官方 侧滑 drawerlayout的更多相关文章
- MVP学习笔记——参考Google官方demo
demo地址:https://github.com/googlesamples/android-architecture 在这个项目里,每个包的分工都很明确,大体上来说,一个包会对应一个界面.一个界面 ...
- Data Binding Guide——google官方文档翻译(下)
这篇博客是Data Binding Guide官网文档翻译的下篇.假设没看过前半部分翻译的能够先看Data Binding Guide--google官方文档翻译(上) 一,数据对象 不论什么不含业 ...
- android SwipeRefreshLayout google官方下拉刷新控件
下拉刷新功能之前一直使用的是XlistView很方便我前面的博客有介绍 SwipeRefreshLayout是google官方推出的下拉刷新控件使用方法也比较简单 今天就来使用下SwipeRefres ...
- 【收藏】Android屏幕适配全攻略(最权威的Google官方适配指导)
来源:http://blog.csdn.net/zhaokaiqiang1992 更多:Android AutoLayout全新的适配方式, 堪称适配终结者 Android的屏幕适配一直以来都在折磨着 ...
- [转]Android UI:看看Google官方自定义带旋转动画的ImageView-----RotateImageView怎么写(附 图片淡入淡出效果)
http://blog.csdn.net/yanzi1225627/article/details/22439119 众所周知,想要让ImageView旋转的话,可以用setRotation()让其围 ...
- Android菜鸟的成长笔记(28)——Google官方对Andoird 2.x提供的ActionBar支持
在Google官方Android设计指南中(链接:http://www.apkbus.com/design/get-started/ui-overview.html)有一个新特性就是自我标识,也就是宣 ...
- google官方的下拉刷新+自定义上拉加载更多
转载请标注转载:http://blog.csdn.net/oqihaogongyuan/article/details/50949118 google官方的下拉刷新+自定义上拉加载更多 现在很多app ...
- Android M以上运行时权限(Google官方出品)
转载请注明出处:http://www.cnblogs.com/cnwutianhao/p/6690152.html 网上运行时权限的例子.Demo无计其数,但是和Google官方出品的比起来,都显得很 ...
- Google官方MVP模式示例项目解析 todo-mvp
转载请注明出处:http://www.cnblogs.com/cnwutianhao/p/6700668.html 引言:在Google没有给出一套权威的架构实现之前,很多App项目在架构方面都有或多 ...
随机推荐
- Cookie&Session
Cookie&Session 背景:Cookie和Session的原理.作用及如何设置和相关面试. 一.诞生背景 HTTP是无状态的,即服务器无法知道两个请求是否来自同一个浏览器,也就是服务器 ...
- 什么时候使用redis?什么时候使用memcache?
要清楚为什么,redis具有高可用特性,并且可固化,但特性有时候不能成为选择他的理由,一些业务场景中并不需要这样的特性. 什么时候倾向于选择redis? 1.复杂数据结构 value是哈希,列表, ...
- HTTP与HTTPS之面试必备
本文主要讲解Http与https的区别,以及https是怎样加密来保证安全的. 首先讲这俩个协议的简单区别: HTTP:超文本传输协议. HTTPS:安全套接字层超文本传输协议HTTP+SSL HTT ...
- scrapy xpath用法
一.实验环境 1.Windows7x64_SP1 2.anaconda3 + python3.7.3(anaconda集成,不需单独安装) 3.scrapy1.6.0 二.用法举例 1.开启scrap ...
- npm install 安装很慢
npm install 安装很慢 设置国内镜像 npm config set registry https://registry.npm.taobao.org npm install
- 实时计算大数据处理的基石-Google Dataflow
此文选自Google大神Tyler Akidau的另一篇文章:Streaming 102: The world beyond batch 欢迎回来!如果您错过了我以前的帖子,Streaming ...
- 结合suctf-upload labs-RougeMysql再学习
这篇主要记录一下这道题目的预期解法 做这道题首先要在自己的vps搭建一个rouge mysql,里面要填写需要读取客户端的文件名,即我们上传的phar文件路径 先搭一个rouge mysql测试看看: ...
- ssh-key生成密钥及SSH无密码登录的配置
文章作者:foochane 原文链接:https://foochane.cn/article/2019061601.html 1 ssh-keygen命令 ssh-keygen命令说明: -t :指 ...
- swith case判断
swith case是js中的一种判断方式 应用于变量或表达式在不同值情况下的不同操作,每一种case结束都要加break结束整个判断 var num = 2; switch(num){ case 0 ...
- Win10下安装python3.x+pycharm+autopep8
一.安装Python3.X 1.Pythong官方网站:http://python.org/getit/ 下载windows的安装包.有以下几个选项: 这里选择windows x86-64 exc ...