Android DrawerLayout抽屉效果

来源:互联网 发布:星际淘宝网起点 编辑:程序博客网 时间:2024/04/30 13:02

官网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?在CODE上查看代码片派生到我的代码片
  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.   
  7.     <FrameLayout  
  8.         android:id="@+id/content_frame"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" />  
  11.   
  12.     <ListView  
  13.         android:id="@+id/left_drawer"  
  14.         android:layout_width="240dp"  
  15.         android:layout_height="match_parent"  
  16.         android:layout_gravity="right"  
  17.         android:choiceMode="singleChoice"  
  18.         android:divider="@android:color/transparent"  
  19.         android:dividerHeight="0dp"  
  20.         android:background="#111"/>  
  21.     <!--   
  22.         android:choiceMode  选中状态 跟itemclick没有冲突  
  23.                 none              值为0,表示无选择模式;   
  24.                 singleChoice      值为1,表示最多可以有一项被选中;  
  25.                 multipleChoice    值为2,表示可以多项被选中。  
  26.                   
  27.         android:layout_gravity  left或right  left或start   right或end  
  28.             表示在抽屉里的效果是从左到右还是从右到左出现  
  29.      -->  
  30. </android.support.v4.widget.DrawerLayout>  

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