Home | History | Annotate | Download | only in navigationdrawer
      1 /*
      2  * Copyright (C) 2014 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.example.android.navigationdrawer;
     18 
     19 import android.app.Activity;
     20 import android.app.Fragment;
     21 import android.app.FragmentManager;
     22 import android.app.FragmentTransaction;
     23 import android.app.SearchManager;
     24 import android.content.Intent;
     25 import android.content.res.Configuration;
     26 import android.os.Bundle;
     27 import android.support.v4.app.ActionBarDrawerToggle;
     28 import android.support.v4.view.GravityCompat;
     29 import android.support.v4.widget.DrawerLayout;
     30 import android.support.v7.widget.RecyclerView;
     31 import android.view.LayoutInflater;
     32 import android.view.Menu;
     33 import android.view.MenuItem;
     34 import android.view.View;
     35 import android.view.ViewGroup;
     36 import android.widget.ImageView;
     37 import android.widget.Toast;
     38 
     39 import java.util.Locale;
     40 
     41 /**
     42  * This example illustrates a common usage of the DrawerLayout widget
     43  * in the Android support library.
     44  * <p/>
     45  * <p>When a navigation (left) drawer is present, the host activity should detect presses of
     46  * the action bar's Up affordance as a signal to open and close the navigation drawer. The
     47  * ActionBarDrawerToggle facilitates this behavior.
     48  * Items within the drawer should fall into one of two categories:</p>
     49  * <p/>
     50  * <ul>
     51  * <li><strong>View switches</strong>. A view switch follows the same basic policies as
     52  * list or tab navigation in that a view switch does not create navigation history.
     53  * This pattern should only be used at the root activity of a task, leaving some form
     54  * of Up navigation active for activities further down the navigation hierarchy.</li>
     55  * <li><strong>Selective Up</strong>. The drawer allows the user to choose an alternate
     56  * parent for Up navigation. This allows a user to jump across an app's navigation
     57  * hierarchy at will. The application should treat this as it treats Up navigation from
     58  * a different task, replacing the current task stack using TaskStackBuilder or similar.
     59  * This is the only form of navigation drawer that should be used outside of the root
     60  * activity of a task.</li>
     61  * </ul>
     62  * <p/>
     63  * <p>Right side drawers should be used for actions, not navigation. This follows the pattern
     64  * established by the Action Bar that navigation should be to the left and actions to the right.
     65  * An action should be an operation performed on the current contents of the window,
     66  * for example enabling or disabling a data overlay on top of the current content.</p>
     67  */
     68 public class NavigationDrawerActivity extends Activity implements PlanetAdapter.OnItemClickListener {
     69     private DrawerLayout mDrawerLayout;
     70     private RecyclerView mDrawerList;
     71     private ActionBarDrawerToggle mDrawerToggle;
     72 
     73     private CharSequence mDrawerTitle;
     74     private CharSequence mTitle;
     75     private String[] mPlanetTitles;
     76 
     77     @Override
     78     protected void onCreate(Bundle savedInstanceState) {
     79         super.onCreate(savedInstanceState);
     80         setContentView(R.layout.activity_navigation_drawer);
     81 
     82         mTitle = mDrawerTitle = getTitle();
     83         mPlanetTitles = getResources().getStringArray(R.array.planets_array);
     84         mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
     85         mDrawerList = (RecyclerView) findViewById(R.id.left_drawer);
     86 
     87         // set a custom shadow that overlays the main content when the drawer opens
     88         mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
     89         // improve performance by indicating the list if fixed size.
     90         mDrawerList.setHasFixedSize(true);
     91 
     92         // set up the drawer's list view with items and click listener
     93         mDrawerList.setAdapter(new PlanetAdapter(mPlanetTitles, this));
     94         // enable ActionBar app icon to behave as action to toggle nav drawer
     95         getActionBar().setDisplayHomeAsUpEnabled(true);
     96         getActionBar().setHomeButtonEnabled(true);
     97 
     98         // ActionBarDrawerToggle ties together the the proper interactions
     99         // between the sliding drawer and the action bar app icon
    100         mDrawerToggle = new ActionBarDrawerToggle(
    101                 this,                  /* host Activity */
    102                 mDrawerLayout,         /* DrawerLayout object */
    103                 R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
    104                 R.string.drawer_open,  /* "open drawer" description for accessibility */
    105                 R.string.drawer_close  /* "close drawer" description for accessibility */
    106         ) {
    107             public void onDrawerClosed(View view) {
    108                 getActionBar().setTitle(mTitle);
    109                 invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
    110             }
    111 
    112             public void onDrawerOpened(View drawerView) {
    113                 getActionBar().setTitle(mDrawerTitle);
    114                 invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
    115             }
    116         };
    117         mDrawerLayout.setDrawerListener(mDrawerToggle);
    118 
    119         if (savedInstanceState == null) {
    120             selectItem(0);
    121         }
    122     }
    123 
    124 
    125     @Override
    126     public boolean onCreateOptionsMenu(Menu menu) {
    127         // Inflate the menu; this adds items to the action bar if it is present.
    128         getMenuInflater().inflate(R.menu.navigation_drawer, menu);
    129         return true;
    130     }
    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);
    138         return super.onPrepareOptionsMenu(menu);
    139     }
    140 
    141     @Override
    142     public boolean onOptionsItemSelected(MenuItem item) {
    143         // The action bar home/up action should open or close the drawer.
    144         // ActionBarDrawerToggle will take care of this.
    145         if (mDrawerToggle.onOptionsItemSelected(item)) {
    146             return true;
    147         }
    148         // Handle action buttons
    149         switch (item.getItemId()) {
    150             case R.id.action_websearch:
    151                 // create intent to perform web search for this planet
    152                 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
    153                 intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
    154                 // catch event that there's no activity to handle intent
    155                 if (intent.resolveActivity(getPackageManager()) != null) {
    156                     startActivity(intent);
    157                 } else {
    158                     Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
    159                 }
    160                 return true;
    161             default:
    162                 return super.onOptionsItemSelected(item);
    163         }
    164     }
    165 
    166     /* The click listener for RecyclerView in the navigation drawer */
    167     @Override
    168     public void onClick(View view, int position) {
    169         selectItem(position);
    170     }
    171 
    172     private void selectItem(int position) {
    173         // update the main content by replacing fragments
    174         Fragment fragment = PlanetFragment.newInstance(position);
    175 
    176         FragmentManager fragmentManager = getFragmentManager();
    177         FragmentTransaction ft = fragmentManager.beginTransaction();
    178         ft.replace(R.id.content_frame, fragment);
    179         ft.commit();
    180 
    181         // update selected item title, then close the drawer
    182         setTitle(mPlanetTitles[position]);
    183         mDrawerLayout.closeDrawer(mDrawerList);
    184     }
    185 
    186     @Override
    187     public void setTitle(CharSequence title) {
    188         mTitle = title;
    189         getActionBar().setTitle(mTitle);
    190     }
    191 
    192     /**
    193      * When using the ActionBarDrawerToggle, you must call it during
    194      * onPostCreate() and onConfigurationChanged()...
    195      */
    196 
    197     @Override
    198     protected void onPostCreate(Bundle savedInstanceState) {
    199         super.onPostCreate(savedInstanceState);
    200         // Sync the toggle state after onRestoreInstanceState has occurred.
    201         mDrawerToggle.syncState();
    202     }
    203 
    204     @Override
    205     public void onConfigurationChanged(Configuration newConfig) {
    206         super.onConfigurationChanged(newConfig);
    207         // Pass any configuration change to the drawer toggls
    208         mDrawerToggle.onConfigurationChanged(newConfig);
    209     }
    210 
    211     /**
    212      * Fragment that appears in the "content_frame", shows a planet
    213      */
    214     public static class PlanetFragment extends Fragment {
    215         public static final String ARG_PLANET_NUMBER = "planet_number";
    216 
    217         public PlanetFragment() {
    218             // Empty constructor required for fragment subclasses
    219         }
    220 
    221         public static Fragment newInstance(int position) {
    222             Fragment fragment = new PlanetFragment();
    223             Bundle args = new Bundle();
    224             args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
    225             fragment.setArguments(args);
    226             return fragment;
    227         }
    228 
    229         @Override
    230         public View onCreateView(LayoutInflater inflater, ViewGroup container,
    231                                  Bundle savedInstanceState) {
    232             View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
    233             int i = getArguments().getInt(ARG_PLANET_NUMBER);
    234             String planet = getResources().getStringArray(R.array.planets_array)[i];
    235 
    236             int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
    237                     "drawable", getActivity().getPackageName());
    238             ImageView iv = ((ImageView) rootView.findViewById(R.id.image));
    239             iv.setImageResource(imageId);
    240 
    241             getActivity().setTitle(planet);
    242             return rootView;
    243         }
    244     }
    245 }
    246