Advertisement
Guest User

NavigationDrawerFragment

a guest
Jan 23rd, 2014
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.65 KB | None | 0 0
  1. import android.app.Activity;
  2. import android.content.SharedPreferences;
  3. import android.content.res.Configuration;
  4. import android.os.Bundle;
  5. import android.preference.PreferenceManager;
  6. import android.support.v4.app.ActionBarDrawerToggle;
  7. import android.support.v4.app.Fragment;
  8. import android.support.v4.view.GravityCompat;
  9. import android.support.v4.widget.DrawerLayout;
  10. import android.support.v7.app.ActionBar;
  11. import android.support.v7.app.ActionBarActivity;
  12. import android.view.LayoutInflater;
  13. import android.view.Menu;
  14. import android.view.MenuInflater;
  15. import android.view.MenuItem;
  16. import android.view.View;
  17. import android.view.ViewGroup;
  18. import android.widget.AdapterView;
  19. import android.widget.ArrayAdapter;
  20. import android.widget.ListView;
  21.  
  22. import com.example.android.R;
  23.  
  24. /**
  25.  * Fragment used for managing interactions for and presentation of a navigation drawer.
  26.  * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
  27.  * design guidelines</a> for a complete explanation of the behaviors implemented here.
  28.  */
  29. public class NavigationDrawerFragment extends Fragment {
  30.     /**
  31.      * Remember the position of the selected item.
  32.      */
  33.     private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
  34.  
  35.     /**
  36.      * Per the design guidelines, you should show the drawer on launch until the user manually
  37.      * expands it. This shared preference tracks this.
  38.      */
  39.     private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
  40.  
  41.     /**
  42.      * A pointer to the current callbacks instance (the Activity).
  43.      */
  44.     private NavigationDrawerCallbacks mCallbacks;
  45.  
  46.     /**
  47.      * Helper component that ties the action bar to the navigation drawer.
  48.      */
  49.     private ActionBarDrawerToggle mDrawerToggle;
  50.  
  51.     private DrawerLayout mDrawerLayout;
  52.     private ListView mDrawerListView;
  53.     private View mFragmentContainerView;
  54.  
  55.     private int mCurrentSelectedPosition = 0;
  56.     private boolean mFromSavedInstanceState;
  57.     private boolean mUserLearnedDrawer;
  58.  
  59.     public NavigationDrawerFragment() {
  60.     }
  61.  
  62.     @Override
  63.     public void onCreate(Bundle savedInstanceState) {
  64.         super.onCreate(savedInstanceState);
  65.  
  66.         // Read in the flag indicating whether or not the user has demonstrated awareness of the
  67.         // drawer. See PREF_USER_LEARNED_DRAWER for details.
  68.         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
  69.         mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
  70.  
  71.         if (savedInstanceState != null) {
  72.             mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
  73.             mFromSavedInstanceState = true;
  74.         }
  75.  
  76.         // Select either the default item (0) or the last selected item.
  77.         selectItem(mCurrentSelectedPosition);
  78.     }
  79.  
  80.     @Override
  81.     public void onActivityCreated (Bundle savedInstanceState) {
  82.         super.onActivityCreated(savedInstanceState);
  83.         // Indicate that this fragment would like to influence the set of actions in the action bar.
  84.         setHasOptionsMenu(true);
  85.     }
  86.  
  87.     @Override
  88.     public View onCreateView(LayoutInflater inflater, ViewGroup container,
  89.                              Bundle savedInstanceState) {
  90.         mDrawerListView = (ListView) inflater.inflate(
  91.                 R.layout.fragment_navigation_drawer, container, false);
  92.         mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  93.             @Override
  94.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  95.                 selectItem(position);
  96.             }
  97.         });
  98.         mDrawerListView.setAdapter(new ArrayAdapter<String>(
  99.                 getActionBar().getThemedContext(),
  100.                 android.R.layout.simple_list_item_1,
  101.                 android.R.id.text1,
  102.                 new String[]{
  103.                         getString(R.string.nav_home),
  104.                         getString(R.string.nav_foo)
  105.                 }));
  106.         mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
  107.         return mDrawerListView;
  108.     }
  109.  
  110.     public boolean isDrawerOpen() {
  111.         return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
  112.     }
  113.  
  114.     /**
  115.      * Users of this fragment must call this method to set up the navigation drawer interactions.
  116.      *
  117.      * @param fragmentId   The android:id of this fragment in its activity's layout.
  118.      * @param drawerLayout The DrawerLayout containing this fragment's UI.
  119.      */
  120.     public void setUp(int fragmentId, DrawerLayout drawerLayout) {
  121.         mFragmentContainerView = getActivity().findViewById(fragmentId);
  122.         mDrawerLayout = drawerLayout;
  123.  
  124.         // set a custom shadow that overlays the main content when the drawer opens
  125.         mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
  126.         // set up the drawer's list view with items and click listener
  127.  
  128.         ActionBar actionBar = getActionBar();
  129.         actionBar.setDisplayHomeAsUpEnabled(true);
  130.         actionBar.setHomeButtonEnabled(true);
  131.  
  132.         // ActionBarDrawerToggle ties together the the proper interactions
  133.         // between the navigation drawer and the action bar app icon.
  134.         mDrawerToggle = new ActionBarDrawerToggle(
  135.                 getActivity(),                    /* host Activity */
  136.                 mDrawerLayout,                    /* DrawerLayout object */
  137.                 R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
  138.                 R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
  139.                 R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
  140.         ) {
  141.             @Override
  142.             public void onDrawerClosed(View drawerView) {
  143.                 super.onDrawerClosed(drawerView);
  144.                 if (!isAdded()) {
  145.                     return;
  146.                 }
  147.  
  148.                 getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
  149.             }
  150.  
  151.             @Override
  152.             public void onDrawerOpened(View drawerView) {
  153.                 super.onDrawerOpened(drawerView);
  154.                 if (!isAdded()) {
  155.                     return;
  156.                 }
  157.  
  158.                 if (!mUserLearnedDrawer) {
  159.                     // The user manually opened the drawer; store this flag to prevent auto-showing
  160.                     // the navigation drawer automatically in the future.
  161.                     mUserLearnedDrawer = true;
  162.                     SharedPreferences sp = PreferenceManager
  163.                             .getDefaultSharedPreferences(getActivity());
  164.                     sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
  165.                 }
  166.  
  167.                 getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
  168.             }
  169.         };
  170.  
  171.         // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
  172.         // per the navigation drawer design guidelines.
  173.         if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
  174.             mDrawerLayout.openDrawer(mFragmentContainerView);
  175.         }
  176.  
  177.         // Defer code dependent on restoration of previous instance state.
  178.         mDrawerLayout.post(new Runnable() {
  179.             @Override
  180.             public void run() {
  181.                 mDrawerToggle.syncState();
  182.             }
  183.         });
  184.  
  185.         mDrawerLayout.setDrawerListener(mDrawerToggle);
  186.     }
  187.  
  188.     private void selectItem(int position) {
  189.         mCurrentSelectedPosition = position;
  190.         if (mDrawerListView != null) {
  191.             mDrawerListView.setItemChecked(position, true);
  192.         }
  193.         if (mDrawerLayout != null) {
  194.             mDrawerLayout.closeDrawer(mFragmentContainerView);
  195.         }
  196.         if (mCallbacks != null) {
  197.             mCallbacks.onNavigationDrawerItemSelected(position);
  198.         }
  199.     }
  200.  
  201.     @Override
  202.     public void onAttach(Activity activity) {
  203.         super.onAttach(activity);
  204.         try {
  205.             mCallbacks = (NavigationDrawerCallbacks) activity;
  206.         } catch (ClassCastException e) {
  207.             throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
  208.         }
  209.     }
  210.  
  211.     @Override
  212.     public void onDetach() {
  213.         super.onDetach();
  214.         mCallbacks = null;
  215.     }
  216.  
  217.     @Override
  218.     public void onSaveInstanceState(Bundle outState) {
  219.         super.onSaveInstanceState(outState);
  220.         outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
  221.     }
  222.  
  223.     @Override
  224.     public void onConfigurationChanged(Configuration newConfig) {
  225.         super.onConfigurationChanged(newConfig);
  226.         // Forward the new configuration the drawer toggle component.
  227.         mDrawerToggle.onConfigurationChanged(newConfig);
  228.     }
  229.  
  230.     @Override
  231.     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  232.         // If the drawer is open, show the global app actions in the action bar. See also
  233.         // showGlobalContextActionBar, which controls the top-left area of the action bar.
  234.         if (mDrawerLayout != null && isDrawerOpen()) {
  235.             inflater.inflate(R.menu.global, menu);
  236.             showGlobalContextActionBar();
  237.         }
  238.         super.onCreateOptionsMenu(menu, inflater);
  239.     }
  240.  
  241.     @Override
  242.     public boolean onOptionsItemSelected(MenuItem item) {
  243.         if (mDrawerToggle.onOptionsItemSelected(item)) {
  244.             return true;
  245.         }
  246.         /*
  247.         if (item.getItemId() == R.id.action_example) {
  248.             Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
  249.             return true;
  250.         }*/
  251.  
  252.         return super.onOptionsItemSelected(item);
  253.     }
  254.  
  255.     /**
  256.      * Per the navigation drawer design guidelines, updates the action bar to show the global app
  257.      * 'context', rather than just what's in the current screen.
  258.      */
  259.     private void showGlobalContextActionBar() {
  260.         ActionBar actionBar = getActionBar();
  261.         actionBar.setDisplayShowTitleEnabled(true);
  262.         actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  263.         actionBar.setTitle(R.string.app_name);
  264.     }
  265.  
  266.     private ActionBar getActionBar() {
  267.         return ((ActionBarActivity) getActivity()).getSupportActionBar();
  268.     }
  269.  
  270.     /**
  271.      * Callbacks interface that all activities using this fragment must implement.
  272.      */
  273.     public static interface NavigationDrawerCallbacks {
  274.         /**
  275.          * Called when an item in the navigation drawer is selected.
  276.          */
  277.         void onNavigationDrawerItemSelected(int position);
  278.     }
  279. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement