官网GUIDE:http://developer.android.com/training/implementing-navigation/nav-drawer.html

官网示例:NavigationDrawer.zip

android.support.v4.widget.DrawerLayout 抽屉layout。该widget只能实现从左向右、从右向左

openDrawer(), closeDrawer(), isDrawerOpen()

下面贴一下示例的主要的布局文件 和 activity实现

activity_main.xml

[html] view plaincopyprint?
  1. <android.support.v4.widget.DrawerLayout
  2. xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/drawer_layout"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent">
  6. <FrameLayout
  7. android:id="@+id/content_frame"
  8. android:layout_width="match_parent"
  9. android:layout_height="match_parent" />
  10. <ListView
  11. android:id="@+id/left_drawer"
  12. android:layout_width="240dp"
  13. android:layout_height="match_parent"
  14. android:layout_gravity="right"
  15. android:choiceMode="singleChoice"
  16. android:divider="@android:color/transparent"
  17. android:dividerHeight="0dp"
  18. android:background="#111"/>
  19. <!--
  20. android:choiceMode  选中状态 跟itemclick没有冲突
  21. none              值为0,表示无选择模式;
  22. singleChoice      值为1,表示最多可以有一项被选中;
  23. multipleChoice    值为2,表示可以多项被选中。
  24. android:layout_gravity  left或right  left或start   right或end
  25. 表示在抽屉里的效果是从左到右还是从右到左出现
  26. -->
  27. </android.support.v4.widget.DrawerLayout>
[java] view plaincopyprint?
  1. package com.jackie.drawerlayout;
  2. /*
  3. * Copyright 2013 The Android Open Source Project
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. *     http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. import java.util.Locale;
  18. import android.app.Activity;
  19. import android.app.Fragment;
  20. import android.app.FragmentManager;
  21. import android.app.SearchManager;
  22. import android.content.Intent;
  23. import android.content.res.Configuration;
  24. import android.os.Bundle;
  25. import android.support.v4.app.ActionBarDrawerToggle;
  26. import android.support.v4.view.GravityCompat;
  27. import android.support.v4.widget.DrawerLayout;
  28. import android.view.LayoutInflater;
  29. import android.view.Menu;
  30. import android.view.MenuInflater;
  31. import android.view.MenuItem;
  32. import android.view.View;
  33. import android.view.ViewGroup;
  34. import android.widget.AdapterView;
  35. import android.widget.ArrayAdapter;
  36. import android.widget.ImageView;
  37. import android.widget.ListView;
  38. import android.widget.Toast;
  39. /**
  40. * This example illustrates a common usage of the DrawerLayout widget
  41. * in the Android support library.
  42. * <p/>
  43. * <p>When a navigation (left) drawer is present, the host activity should detect presses of
  44. * the action bar's Up affordance as a signal to open and close the navigation drawer. The
  45. * ActionBarDrawerToggle facilitates this behavior.
  46. * Items within the drawer should fall into one of two categories:</p>
  47. * <p/>
  48. * <ul>
  49. * <li><strong>View switches</strong>. A view switch follows the same basic policies as
  50. * list or tab navigation in that a view switch does not create navigation history.
  51. * This pattern should only be used at the root activity of a task, leaving some form
  52. * of Up navigation active for activities further down the navigation hierarchy.</li>
  53. * <li><strong>Selective Up</strong>. The drawer allows the user to choose an alternate
  54. * parent for Up navigation. This allows a user to jump across an app's navigation
  55. * hierarchy at will. The application should treat this as it treats Up navigation from
  56. * a different task, replacing the current task stack using TaskStackBuilder or similar.
  57. * This is the only form of navigation drawer that should be used outside of the root
  58. * activity of a task.</li>
  59. * </ul>
  60. * <p/>
  61. * <p>Right side drawers should be used for actions, not navigation. This follows the pattern
  62. * established by the Action Bar that navigation should be to the left and actions to the right.
  63. * An action should be an operation performed on the current contents of the window,
  64. * for example enabling or disabling a data overlay on top of the current content.</p>
  65. */
  66. public class MainActivity extends Activity {
  67. private DrawerLayout mDrawerLayout;
  68. private ListView mDrawerList;
  69. private ActionBarDrawerToggle mDrawerToggle;
  70. private CharSequence mDrawerTitle;
  71. private CharSequence mTitle;
  72. private String[] mPlanetTitles;
  73. @Override
  74. protected void onCreate(Bundle savedInstanceState) {
  75. super.onCreate(savedInstanceState);
  76. setContentView(R.layout.activity_main);
  77. mTitle = mDrawerTitle = getTitle();
  78. mPlanetTitles = getResources().getStringArray(R.array.planets_array);
  79. mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
  80. mDrawerList = (ListView) findViewById(R.id.left_drawer);//抽屉里的view
  81. // set a custom shadow that overlays the main content when the drawer opens
  82. mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);//设置shadow
  83. // set up the drawer's list view with items and click listener
  84. mDrawerList.setAdapter(new ArrayAdapter<String>(this,
  85. R.layout.drawer_list_item, mPlanetTitles));
  86. mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
  87. // enable ActionBar app icon to behave as action to toggle nav drawer   需要api level 11
  88. getActionBar().setDisplayHomeAsUpEnabled(true);//给home icon的左边加上一个返回的图标
  89. getActionBar().setHomeButtonEnabled(true); //需要api level 14  使用home-icon 可点击
  90. // ActionBarDrawerToggle ties together the the proper interactions
  91. // between the sliding drawer and the action bar app icon
  92. mDrawerToggle = new ActionBarDrawerToggle(//v4控件  actionbar上的抽屉开关
  93. this,                  /* host Activity */
  94. mDrawerLayout,         /* DrawerLayout object */
  95. R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */     //上一级图标 返回图标
  96. R.string.drawer_open,  /* "open drawer" description for accessibility */
  97. R.string.drawer_close  /* "close drawer" description for accessibility */
  98. ) {
  99. public void onDrawerClosed(View view) {//抽屉关闭后
  100. getActionBar().setTitle(mDrawerTitle);
  101. invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
  102. }
  103. public void onDrawerOpened(View drawerView) {//抽屉打开后
  104. getActionBar().setTitle(mTitle);
  105. invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
  106. }
  107. @Override
  108. public boolean onOptionsItemSelected(MenuItem item) {
  109. if (item != null && item.getItemId() == android.R.id.home) {//actionbar上的home icon
  110. //END即gravity.right 从右向左显示   START即left  从左向右弹出显示
  111. if (mDrawerLayout.isDrawerVisible(GravityCompat.END)) {
  112. mDrawerLayout.closeDrawer(GravityCompat.END);//关闭抽屉
  113. } else {
  114. mDrawerLayout.openDrawer(GravityCompat.END);//打开抽屉
  115. }
  116. return true;
  117. }
  118. return false;
  119. }
  120. };
  121. mDrawerLayout.setDrawerListener(mDrawerToggle);//设置抽屉监听
  122. if (savedInstanceState == null) {
  123. //            selectItem(0);
  124. }
  125. }
  126. @Override
  127. public boolean onCreateOptionsMenu(Menu menu) {//加载menu  sdk3.0以后menu包含在actionbar中
  128. MenuInflater inflater = getMenuInflater();
  129. inflater.inflate(R.menu.main, menu);
  130. return super.onCreateOptionsMenu(menu);
  131. }
  132. /* Called whenever we call invalidateOptionsMenu() */
  133. @Override
  134. public boolean onPrepareOptionsMenu(Menu menu) {
  135. // If the nav drawer is open, hide action items related to the content view
  136. boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
  137. menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);//search的显示与drawer的显示相反
  138. return super.onPrepareOptionsMenu(menu);
  139. }
  140. @Override
  141. public boolean onOptionsItemSelected(MenuItem item) {
  142. // The action bar home/up action should open or close the drawer.
  143. // ActionBarDrawerToggle will take care of this.
  144. if (mDrawerToggle.onOptionsItemSelected(item)) {
  145. return true;
  146. }
  147. // Handle action buttons
  148. switch(item.getItemId()) {
  149. case R.id.action_websearch:
  150. // create intent to perform web search for this planet
  151. Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
  152. intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
  153. // catch event that there's no activity to handle intent
  154. if (intent.resolveActivity(getPackageManager()) != null) {
  155. startActivity(intent);
  156. } else {
  157. Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
  158. }
  159. return true;
  160. default:
  161. return super.onOptionsItemSelected(item);
  162. }
  163. }
  164. /* The click listner for ListView in the navigation drawer */
  165. private class DrawerItemClickListener implements ListView.OnItemClickListener {
  166. @Override
  167. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  168. selectItem(position);
  169. }
  170. }
  171. //内容区显示PlanetFragment
  172. private void selectItem(int position) {
  173. // update the main content by replacing fragments
  174. Fragment fragment = new PlanetFragment();
  175. Bundle args = new Bundle();
  176. args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
  177. fragment.setArguments(args);
  178. FragmentManager fragmentManager = getFragmentManager();
  179. fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
  180. // update selected item and title, then close the drawer
  181. //        mDrawerList.setItemChecked(position, true);
  182. //        setTitle(mPlanetTitles[position]);
  183. mDrawerLayout.closeDrawer(mDrawerList);
  184. }
  185. @Override
  186. public void setTitle(CharSequence title) {
  187. mDrawerTitle = title;
  188. getActionBar().setTitle(mDrawerTitle);
  189. }
  190. /**
  191. * When using the ActionBarDrawerToggle, you must call it during
  192. * onPostCreate() and onConfigurationChanged()...
  193. */
  194. @Override
  195. protected void onPostCreate(Bundle savedInstanceState) {
  196. super.onPostCreate(savedInstanceState);
  197. // Sync the toggle state after onRestoreInstanceState has occurred.
  198. mDrawerToggle.syncState();
  199. }
  200. @Override
  201. public void onConfigurationChanged(Configuration newConfig) {
  202. super.onConfigurationChanged(newConfig);
  203. // Pass any configuration change to the drawer toggls
  204. mDrawerToggle.onConfigurationChanged(newConfig);
  205. }
  206. /**
  207. * Fragment that appears in the "content_frame", shows a planet
  208. */
  209. public static class PlanetFragment extends Fragment {
  210. public static final String ARG_PLANET_NUMBER = "planet_number";
  211. public PlanetFragment() {
  212. // Empty constructor required for fragment subclasses
  213. }
  214. @Override
  215. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  216. Bundle savedInstanceState) {
  217. View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
  218. int i = getArguments().getInt(ARG_PLANET_NUMBER);
  219. String planet = getResources().getStringArray(R.array.planets_array)[i];
  220. //查找出 res-drawable资源的id
  221. int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
  222. "drawable", getActivity().getPackageName());
  223. ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
  224. getActivity().setTitle(planet);
  225. return rootView;
  226. }
  227. }
  228. }

Android DrawerLayout抽屉效果相关推荐

  1. android 实现抽屉效果

    android的UI开发确实是一件很有趣的事情,也是一件很有挑战性的事情. 本文章是将自己在开发中的项目中使用到的比较好的抽屉效果的原理以及代码整理后写上来的,以备忘记后可以查阅 抽屉效果的原理很简单 ...

  2. android 右边抽屉,Android实现右边抽屉Drawerlayout效果

    侧边栏是Android应用中很常见的一个界面效果(抽屉效果).而利用DrawerLayout实现右侧栏是相对简单的.而且这个控件自带滑动效果,十分方便. DrawerLayout属于android-s ...

  3. 抽屉效果的实现(DrawerLayout和SlidingMenu的对比)

    在做谷歌电子市场的时候用的是DrawerLayout实现的抽屉效果,在新闻客户端的时候用的是开源框架SlidingMenu来实现的,总的来说,各有个的优点,侧滑(开源框架)实现的效果更好,但是Draw ...

  4. Android 抽屉效果的导航菜单实现

    抽屉效果的导航菜单 看了很多应用,觉得这种侧滑的抽屉效果的菜单很好. 不用切换到另一个页面,也不用去按菜单的硬件按钮,直接在界面上一个按钮点击,菜单就滑出来,而且感觉能放很多东西. 关于实现,搜索了一 ...

  5. android中仿qq最新版抽屉,Android 自定义View实现抽屉效果

    Android 自定义View实现抽屉效果 说明 这个自定义View,没有处理好多点触摸问题 View跟着手指移动,没有采用传统的scrollBy方法,而是通过不停地重新布局子View的方式,来使得子 ...

  6. Android 抽屉效果Demo

    2019独角兽企业重金招聘Python工程师标准>>> Android 抽屉效果Demo. 转载:http://www.adobex.com/android/source/detai ...

  7. android textview抽屉滑动,Android SlidingDrawer 滑动抽屉效果

    效果如上图,想必大家已经在很多应用中看到过了,下面来看看用SlidingDrawer 实现滑动抽屉效果 从Android1.5开始,加入了android.widget.SlidingDrawer类 S ...

  8. android仿腾讯安全管家首页抽屉效果

    [color=red]转载请说明出处[/color] 最近在做公司新产品的设计,看到腾讯安全管家首页的抽屉效果设计的挺不错,一方面可以讲经常使用的功能模块直接显示给用户,另一方面将用户不常用的功能模块 ...

  9. android 3d侧拉抽屉,iOS动画指南 - 4.右拉的3D抽屉效果

    一切的动画其实都是假象,3D效果也是这样.本篇我们来做一个这样的特效. 先忽略掉3D效果,我们先要做的是一个右拉的抽屉效果. 总体思路: 1.创建一个ContainerViewController容器 ...

最新文章

  1. mac mongodb可视化工具_「时序数据库」和MongoDB:第3部分-查询、分析和呈现
  2. 【网络安全】php代码审计-sql注入进阶篇
  3. 六、爬虫中重要的解析库xpath和BeautifulSoup
  4. 转: java web demo的示例
  5. 基于JAVA+Servlet+JSP+MYSQL的银行账户管理系统
  6. 微型计算机主机箱内的所有部件均由,计算机应用基础模拟题
  7. javaScript与MVC
  8. Fiddler—PC上实现手机的抓包
  9. 首都师范 博弈论 3 4 2反复剔除严格劣策略
  10. MATLAB:简单GUI的设计流程
  11. windows 启动 cmd快捷键,类似于 linux “Ctrl+Alt+T“ 启动终端
  12. ajax回调的data,。。。Ajax的回调函数function(data)中,data的返回类型。。。
  13. Manjaro Linux安装QQ和微信
  14. python实现CAPM模型
  15. kotlin版贪吃蛇小游戏
  16. Lua基础教程与实践
  17. 设计模式 “之“ 责任链模式
  18. 工具及方法 - 查看飞机信息
  19. ipad2018电池测试软件,苹果ipad 2018评测
  20. oracle总帐的重估逻辑,OraEBSR12GL日记账业务操作23:汇率重估模板定义

热门文章

  1. 17、江科大stm32视频学习笔记——USART串口协议和USART串口外设
  2. clover安装Mac big sur卡在Attempting system restart...MACH Reboot
  3. 日志管理:如何通过日志实现日志日志可治理
  4. Vue中v-html无法渲染
  5. (译) Conditional Variational Autoencoders 条件式变换自编码机
  6. windows系统如何将 CMD(命令提示符)添加到鼠标右键菜单
  7. 用Python爬一下《中餐厅》绿大暗:我不要你觉得,我只要我觉得
  8. 哀悼CSS 哀悼的时候让页面字体变黑的css
  9. 程序员你知道吗?微信这功能开始收费了~
  10. Java:将大文件拆分工具