当前位置:   article > 正文

Android Studio自带模版:抽屉(DrawerLayout)布局_supportinvalidateoptionsmenu drawerlayout

supportinvalidateoptionsmenu drawerlayout

MainActivity.java

  1. package com.qiufeng.astest;
  2. import android.app.Activity;
  3. import android.support.v7.app.ActionBarActivity;
  4. import android.support.v7.app.ActionBar;
  5. import android.support.v4.app.Fragment;
  6. import android.support.v4.app.FragmentManager;
  7. import android.content.Context;
  8. import android.os.Build;
  9. import android.os.Bundle;
  10. import android.view.Gravity;
  11. import android.view.LayoutInflater;
  12. import android.view.Menu;
  13. import android.view.MenuItem;
  14. import android.view.View;
  15. import android.view.ViewGroup;
  16. import android.support.v4.widget.DrawerLayout;
  17. import android.widget.ArrayAdapter;
  18. import android.widget.TextView;
  19. public class MainActivity extends ActionBarActivity
  20. implements NavigationDrawerFragment.NavigationDrawerCallbacks {
  21. /**
  22. * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
  23. * 用于显示侧栏的fragment
  24. */
  25. private NavigationDrawerFragment mNavigationDrawerFragment;
  26. /**
  27. * Used to store the last screen title. For use in {@link #restoreActionBar()}.
  28. * 在标题上显示上一次选中的item中的文字内容
  29. */
  30. private CharSequence mTitle;
  31. @Override
  32. protected void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.activity_main);
  35. mNavigationDrawerFragment = (NavigationDrawerFragment)
  36. getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
  37. mTitle = getTitle();
  38. //初始化drawer
  39. mNavigationDrawerFragment.setUp(
  40. R.id.navigation_drawer,
  41. (DrawerLayout) findViewById(R.id.drawer_layout));
  42. }
  43. //实现NavigationDrawerFragment中的接口
  44. @Override
  45. public void onNavigationDrawerItemSelected(int position) {
  46. // update the main content by replacing fragments
  47. // 更新content中显示的内容
  48. FragmentManager fragmentManager = getSupportFragmentManager();
  49. fragmentManager.beginTransaction()
  50. .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
  51. .commit();
  52. }
  53. public void onSectionAttached(int number) {
  54. switch (number) {
  55. case 1:
  56. mTitle = getString(R.string.title_section1);
  57. break;
  58. case 2:
  59. mTitle = getString(R.string.title_section2);
  60. break;
  61. case 3:
  62. mTitle = getString(R.string.title_section3);
  63. break;
  64. }
  65. }
  66. public void restoreActionBar() {
  67. ActionBar actionBar = getSupportActionBar();
  68. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  69. actionBar.setDisplayShowTitleEnabled(true);
  70. actionBar.setTitle(mTitle);
  71. }
  72. @Override
  73. public boolean onCreateOptionsMenu(Menu menu) {
  74. if (!mNavigationDrawerFragment.isDrawerOpen()) {
  75. // Only show items in the action bar relevant to this screen
  76. // if the drawer is not showing. Otherwise, let the drawer
  77. // decide what to show in the action bar.
  78. getMenuInflater().inflate(R.menu.main, menu);
  79. restoreActionBar();
  80. return true;
  81. }
  82. return super.onCreateOptionsMenu(menu);
  83. }
  84. @Override
  85. public boolean onOptionsItemSelected(MenuItem item) {
  86. // Handle action bar item clicks here. The action bar will
  87. // automatically handle clicks on the Home/Up button, so long
  88. // as you specify a parent activity in AndroidManifest.xml.
  89. int id = item.getItemId();
  90. //noinspection SimplifiableIfStatement
  91. if (id == R.id.action_settings) {
  92. return true;
  93. }
  94. return super.onOptionsItemSelected(item);
  95. }
  96. /**
  97. * A placeholder fragment containing a simple view.
  98. * 侧栏选中item之后显示的内容fragment
  99. */
  100. public static class PlaceholderFragment extends Fragment {
  101. /**
  102. * The fragment argument representing the section number for this
  103. * fragment.
  104. */
  105. private static final String ARG_SECTION_NUMBER = "section_number";
  106. /**
  107. * Returns a new instance of this fragment for the given section
  108. * number.
  109. */
  110. public static PlaceholderFragment newInstance(int sectionNumber) {
  111. PlaceholderFragment fragment = new PlaceholderFragment();
  112. Bundle args = new Bundle();
  113. args.putInt(ARG_SECTION_NUMBER, sectionNumber);
  114. fragment.setArguments(args);
  115. return fragment;
  116. }
  117. public PlaceholderFragment() {
  118. }
  119. @Override
  120. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  121. Bundle savedInstanceState) {
  122. View rootView = inflater.inflate(R.layout.fragment_main, container, false);
  123. return rootView;
  124. }
  125. @Override
  126. public void onAttach(Activity activity) {
  127. super.onAttach(activity);
  128. ((MainActivity) activity).onSectionAttached(
  129. getArguments().getInt(ARG_SECTION_NUMBER));
  130. }
  131. }
  132. }


抽屉(Drawer)的布局文件

  1. package com.qiufeng.astest;
  2. import android.support.v7.app.ActionBarActivity;
  3. import android.app.Activity;
  4. import android.support.v7.app.ActionBar;
  5. import android.support.v4.app.Fragment;
  6. import android.support.v4.app.ActionBarDrawerToggle;
  7. import android.support.v4.view.GravityCompat;
  8. import android.support.v4.widget.DrawerLayout;
  9. import android.content.SharedPreferences;
  10. import android.content.res.Configuration;
  11. import android.os.Bundle;
  12. import android.preference.PreferenceManager;
  13. import android.view.LayoutInflater;
  14. import android.view.Menu;
  15. import android.view.MenuInflater;
  16. import android.view.MenuItem;
  17. import android.view.View;
  18. import android.view.ViewGroup;
  19. import android.widget.AdapterView;
  20. import android.widget.ArrayAdapter;
  21. import android.widget.ListView;
  22. import android.widget.Toast;
  23. /**
  24. * Fragment used for managing interactions for and presentation of a navigation drawer.
  25. * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
  26. * design guidelines</a> for a complete explanation of the behaviors implemented here.
  27. */
  28. public class NavigationDrawerFragment extends Fragment {
  29. /**
  30. * Remember the position of the selected item.
  31. * 选中item的位置
  32. */
  33. private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
  34. /**
  35. * Per the design guidelines, you should show the drawer on launch until the user manually
  36. * expands it. This shared preference tracks this.
  37. */
  38. private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
  39. /**
  40. * A pointer to the current callbacks instance (the Activity).
  41. */
  42. private NavigationDrawerCallbacks mCallbacks;
  43. /**
  44. * Helper component that ties the action bar to the navigation drawer.
  45. */
  46. private ActionBarDrawerToggle mDrawerToggle;
  47. private DrawerLayout mDrawerLayout;
  48. private ListView mDrawerListView;
  49. private View mFragmentContainerView;
  50. private int mCurrentSelectedPosition = 0;
  51. private boolean mFromSavedInstanceState;
  52. private boolean mUserLearnedDrawer;
  53. public NavigationDrawerFragment() {
  54. }
  55. @Override
  56. public void onCreate(Bundle savedInstanceState) {
  57. super.onCreate(savedInstanceState);
  58. // Read in the flag indicating whether or not the user has demonstrated awareness of the
  59. // drawer. See PREF_USER_LEARNED_DRAWER for details.
  60. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
  61. //默认值为false
  62. mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
  63. if (savedInstanceState != null) {
  64. mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
  65. mFromSavedInstanceState = true;
  66. }
  67. // Select either the default item (0) or the last selected item.
  68. // 默认位置为第一个,或者是显示上一次打开的位置
  69. selectItem(mCurrentSelectedPosition);
  70. }
  71. @Override
  72. public void onActivityCreated(Bundle savedInstanceState) {
  73. super.onActivityCreated(savedInstanceState);
  74. // Indicate that this fragment would like to influence the set of actions in the action bar.
  75. setHasOptionsMenu(true);
  76. }
  77. @Override
  78. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  79. Bundle savedInstanceState) {
  80. mDrawerListView = (ListView) inflater.inflate(
  81. R.layout.fragment_navigation_drawer, container, false);
  82. mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  83. @Override
  84. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  85. selectItem(position);
  86. }
  87. });
  88. mDrawerListView.setAdapter(new ArrayAdapter<String>(
  89. getActionBar().getThemedContext(),
  90. android.R.layout.simple_list_item_1,
  91. android.R.id.text1,
  92. new String[]{
  93. getString(R.string.title_section1),
  94. getString(R.string.title_section2),
  95. getString(R.string.title_section3),
  96. }));
  97. mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
  98. return mDrawerListView;
  99. }
  100. public boolean isDrawerOpen() {
  101. return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
  102. }
  103. /**
  104. * Users of this fragment must call this method to set up the navigation drawer interactions.
  105. *
  106. * @param fragmentId The android:id of this fragment in its activity's layout.
  107. * @param drawerLayout The DrawerLayout containing this fragment's UI.
  108. */
  109. public void setUp(int fragmentId, DrawerLayout drawerLayout) {
  110. mFragmentContainerView = getActivity().findViewById(fragmentId);
  111. mDrawerLayout = drawerLayout;
  112. // set a custom shadow that overlays the main content when the drawer opens
  113. mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
  114. // set up the drawer's list view with items and click listener
  115. ActionBar actionBar = getActionBar();
  116. actionBar.setDisplayHomeAsUpEnabled(true);
  117. actionBar.setHomeButtonEnabled(true);
  118. // ActionBarDrawerToggle ties together the the proper interactions
  119. // between the navigation drawer and the action bar app icon.
  120. mDrawerToggle = new ActionBarDrawerToggle(
  121. getActivity(), /* host Activity */
  122. mDrawerLayout, /* DrawerLayout object */
  123. R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
  124. R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
  125. R.string.navigation_drawer_close /* "close drawer" description for accessibility */
  126. ) {
  127. @Override
  128. public void onDrawerClosed(View drawerView) {
  129. super.onDrawerClosed(drawerView);
  130. if (!isAdded()) {
  131. return;
  132. }
  133. getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
  134. }
  135. @Override
  136. public void onDrawerOpened(View drawerView) {
  137. super.onDrawerOpened(drawerView);
  138. if (!isAdded()) {
  139. return;
  140. }
  141. //判断用户是否知道drawer的功能
  142. if (!mUserLearnedDrawer) {
  143. // The user manually opened the drawer; store this flag to prevent auto-showing
  144. // the navigation drawer automatically in the future.
  145. mUserLearnedDrawer = true;
  146. SharedPreferences sp = PreferenceManager
  147. .getDefaultSharedPreferences(getActivity());
  148. sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
  149. }
  150. getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
  151. }
  152. };
  153. // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
  154. // per the navigation drawer design guidelines.
  155. if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
  156. mDrawerLayout.openDrawer(mFragmentContainerView);
  157. }
  158. // Defer code dependent on restoration of previous instance state.
  159. mDrawerLayout.post(new Runnable() {
  160. @Override
  161. public void run() {
  162. mDrawerToggle.syncState();
  163. }
  164. });
  165. mDrawerLayout.setDrawerListener(mDrawerToggle);
  166. }
  167. private void selectItem(int position) {
  168. mCurrentSelectedPosition = position;
  169. if (mDrawerListView != null) {
  170. mDrawerListView.setItemChecked(position, true);
  171. }
  172. if (mDrawerLayout != null) {
  173. mDrawerLayout.closeDrawer(mFragmentContainerView);
  174. }
  175. if (mCallbacks != null) {
  176. mCallbacks.onNavigationDrawerItemSelected(position);
  177. }
  178. }
  179. @Override
  180. public void onAttach(Activity activity) {
  181. super.onAttach(activity);
  182. try {
  183. mCallbacks = (NavigationDrawerCallbacks) activity;
  184. } catch (ClassCastException e) {
  185. throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
  186. }
  187. }
  188. @Override
  189. public void onDetach() {
  190. super.onDetach();
  191. mCallbacks = null;
  192. }
  193. @Override
  194. public void onSaveInstanceState(Bundle outState) {
  195. super.onSaveInstanceState(outState);
  196. //保存STATE_SELECTED_POSITION
  197. outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
  198. }
  199. /**
  200. * 在Android开发中,如果某些事件触发(例如:旋屏事件),
  201. * 则Activity会重新调用onCreate方法,对Activity重新初始化,
  202. * 这样不仅效率低,而且会造成数据丢失,解决办法是重写onConfigurationChanged方法,
  203. * 并在AndroidManifest.xml中对Activity声明configChanges,
  204. * 这样特定事件触发就会调用onConfigurationChanged方法,
  205. * 而不是onCreate方法重新初始化。
  206. * */
  207. @Override
  208. public void onConfigurationChanged(Configuration newConfig) {
  209. super.onConfigurationChanged(newConfig);
  210. // Forward the new configuration the drawer toggle component.
  211. mDrawerToggle.onConfigurationChanged(newConfig);
  212. }
  213. @Override
  214. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  215. // If the drawer is open, show the global app actions in the action bar. See also
  216. // showGlobalContextActionBar, which controls the top-left area of the action bar.
  217. if (mDrawerLayout != null && isDrawerOpen()) {
  218. inflater.inflate(R.menu.global, menu);
  219. showGlobalContextActionBar();
  220. }
  221. super.onCreateOptionsMenu(menu, inflater);
  222. }
  223. @Override
  224. public boolean onOptionsItemSelected(MenuItem item) {
  225. if (mDrawerToggle.onOptionsItemSelected(item)) {
  226. return true;
  227. }
  228. if (item.getItemId() == R.id.action_example) {
  229. Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
  230. return true;
  231. }
  232. return super.onOptionsItemSelected(item);
  233. }
  234. /**
  235. * Per the navigation drawer design guidelines, updates the action bar to show the global app
  236. * 'context', rather than just what's in the current screen.
  237. */
  238. private void showGlobalContextActionBar() {
  239. ActionBar actionBar = getActionBar();
  240. actionBar.setDisplayShowTitleEnabled(true);
  241. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  242. actionBar.setTitle(R.string.app_name);
  243. }
  244. private ActionBar getActionBar() {
  245. return ((ActionBarActivity) getActivity()).getSupportActionBar();
  246. }
  247. /**
  248. * Callbacks interface用到这个fragment时都必须实现这个接口
  249. */
  250. public static interface NavigationDrawerCallbacks {
  251. /**
  252. * Called when an item in the navigation drawer is selected.
  253. */
  254. void onNavigationDrawerItemSelected(int position);
  255. }
  256. }

布局文件:

activity_main.xml

  1. <!-- 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. -->
  2. <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
  4. android:layout_width="match_parent" android:layout_height="match_parent"
  5. tools:context=".MainActivity">
  6. <!-- As the main content view, the view below consumes the entire
  7. space available using match_parent in both dimensions. -->
  8. <FrameLayout
  9. android:id="@+id/container"
  10. android:layout_width="match_parent"
  11. android:layout_height="match_parent" />
  12. <!-- android:layout_gravity="start" tells DrawerLayout to treat
  13. this as a sliding drawer on the left side for left-to-right
  14. languages and on the right side for right-to-left languages.
  15. If you're not building against API 17 or higher, use
  16. android:layout_gravity="left" instead. -->
  17. <!-- The drawer is given a fixed width in dp and extends the full height of
  18. the container. -->
  19. <fragment android:id="@+id/navigation_drawer"
  20. android:layout_width="@dimen/navigation_drawer_width"
  21. android:layout_height="match_parent"
  22. android:layout_gravity="start"
  23. android:name="com.qiufeng.astest.NavigationDrawerFragment"
  24. tools:layout="@layout/fragment_navigation_drawer" />
  25. </android.support.v4.widget.DrawerLayout>


fragment_main.xml

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  3. android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  4. android:paddingRight="@dimen/activity_horizontal_margin"
  5. android:paddingTop="@dimen/activity_vertical_margin"
  6. android:paddingBottom="@dimen/activity_vertical_margin"
  7. tools:context=".MainActivity$PlaceholderFragment">
  8. <TextView
  9. android:id="@+id/section_label"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content" />
  12. </RelativeLayout>

fragment_navigation_drawer.xml

  1. <ListView xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:choiceMode="singleChoice"
  6. android:divider="@android:color/transparent"
  7. android:dividerHeight="0dp"
  8. android:background="#DDDDDD"
  9. tools:context=".NavigationDrawerFragment"
  10. />


声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号