Drawer Layout
http://developer.android.com/training/implementing-navigation/nav-drawer.html#DrawerLayout
1 <menu xmlns:android="http://schemas.android.com/apk/res/android" > 2 <!-- 3 R.menu.main 4 android:showAsAction="ifRoom|withText" 5 如果有空间的话,就实现图标和文字。 6 --> 7 <item 8 android:id="@+id/action_websearch" 9 android:icon="@drawable/action_search" 10 android:showAsAction="ifRoom|withText" 11 android:title="@string/action_websearch"/> 12 </menu>
1 <resources>
2
3 <string name="app_name">左侧菜单</string>
4
5 <string-array name="planets_array">
6 <item>Mercury</item>
7 <item>Venus</item>
8 <item>Earth</item>
9 <item>Mars</item>
10 <item>Jupiter</item>
11 <item>Saturn</item>
12 <item>Uranus</item>
13 <item>Neptune</item>
14 </string-array>
15
16 <string name="drawer_open">打开</string>
17 <string name="drawer_close">关闭</string>
18 <string name="action_websearch">WebSearch</string>
19 <string name="app_not_available">Sorry, there\'s no web browser available</string>
20
21 </resources>
1 <!--
2 【 注意事项 】
3 1、主内容视图一定要是DrawerLayout的第一个子视图。
4 2、主要内容视图宽度和高度匹配父视图,即“match_parent”。
5 3、必须显示指定抽屉视图(如ListView)的android:layout_gravity属性
6 android:layout_gravity="start",从左向右滑出菜单;
7 android:layout_gravity="end", 从右向左滑出菜单;
8 不推荐使用"left"和"right"。
9 4、抽屉视图的宽度以dp为单位,请不要超过320dp(为了总能看到一些主内容视图)
10 -->
11
12
13 <!-- A DrawerLayout is intended to be used as the top-level content view using match_parent
14 for both width and height to consume the full space available. -->
15 <android.support.v4.widget.DrawerLayout
16 xmlns:android="http://schemas.android.com/apk/res/android"
17 android:id="@+id/drawer_layout"
18 android:layout_width="match_parent"
19 android:layout_height="match_parent" >
20
21 <!--
22 As the main content view, the view below consumes the entire
23 space available using match_parent in both dimensions.
24 -->
25 <!-- 在这里面动态插入Fragment -->
26 <FrameLayout
27 android:id="@+id/content_frame"
28 android:layout_width="match_parent"
29 android:layout_height="match_parent" />
30
31 <!--
32 android:layout_gravity="start" tells DrawerLayout to treat
33 this as a sliding drawer on the left side for left-to-right
34 languages and on the right side for right-to-left languages.
35 The drawer is given a fixed width in dp and extends the full height of
36 the container. A solid background is used for contrast
37 with the content view.
38 -->
39
40 <!--
41 android:layout_gravity="start" 从左向右滑动
42 android:layout_gravity="end" 从右向左滑动
43 android:choiceMode="singleChoice" 单选模式
44 -->
45 <ListView
46 android:id="@+id/left_drawer"
47 android:layout_width="240dp"
48 android:layout_height="match_parent"
49 android:layout_gravity="start"
50 android:background="#111"
51 android:choiceMode="singleChoice"
52 android:divider="@android:color/transparent"
53 android:dividerHeight="0dp" />
54
55 </android.support.v4.widget.DrawerLayout>
1 package com.example.android.navigationdrawerexample;
2
3 import java.util.Locale;
4
5 import android.app.Activity;
6 import android.app.Fragment;
7 import android.app.FragmentManager;
8 import android.content.Intent;
9 import android.content.res.Configuration;
10 import android.net.Uri;
11 import android.os.Bundle;
12 import android.support.v4.app.ActionBarDrawerToggle;
13 import android.support.v4.view.GravityCompat;
14 import android.support.v4.widget.DrawerLayout;
15 import android.view.LayoutInflater;
16 import android.view.Menu;
17 import android.view.MenuInflater;
18 import android.view.MenuItem;
19 import android.view.View;
20 import android.view.ViewGroup;
21 import android.widget.AdapterView;
22 import android.widget.ArrayAdapter;
23 import android.widget.ImageView;
24 import android.widget.ListView;
25 import android.widget.Toast;
26
27
28 public class MainActivity extends Activity {
29 private DrawerLayout mDrawerLayout;
30 private ListView mDrawerList;
31
32 /* 1、mDrawerLayout.setDrawerListener(DrawerLayout.DrawerListener);
33 2、ActionBarDrawerToggle是DrawerLayout.DrawerListener的具体实现类;
34 1)改变android.R.id.home图标(构造方法)。
35 2)Drawer拉出、隐藏,带有android.R.id.home动画效果(syncState())。
36 3)监听Drawer拉出、隐藏事件。
37 3、覆写ActionBarDrawerToggle的onDrawerOpened()和onDrawerClosed()以监听抽屉拉出或隐藏事件。
38 */
39 private ActionBarDrawerToggle mDrawerToggle;
40
41 //private CharSequence mDrawerTitle;
42 private CharSequence mTitle;
43 private String[] mPlanetTitles;
44
45 @Override
46 protected void onCreate(Bundle savedInstanceState) {
47 super.onCreate(savedInstanceState);
48 setContentView(R.layout.activity_main);
49
50 mTitle = getTitle();
51 // ListView列表数据
52 mPlanetTitles = getResources().getStringArray(R.array.planets_array);
53 mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
54 mDrawerList = (ListView) findViewById(R.id.left_drawer);
55
56 // set a custom shadow that overlays the main content when the drawer
57 // opens
58 mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
59 // set up the drawer's list view with items and click listener
60 mDrawerList.setAdapter(new ArrayAdapter<String>(this,
61 R.layout.drawer_list_item, mPlanetTitles));
62 mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
63
64 // enable ActionBar app icon to behave as action to toggle nav drawer
65 // 开启ActionBar上APP ICON的功能
66 getActionBar().setDisplayHomeAsUpEnabled(true);
67 getActionBar().setHomeButtonEnabled(true);
68
69 /**
70 * 第4个和第5个参数:打开和关闭的描述资源
71 */
72 mDrawerToggle = new ActionBarDrawerToggle(
73 this,
74 mDrawerLayout,
75 R.drawable.ic_drawer,
76 R.string.drawer_open,
77 R.string.drawer_close) {
78 /** 覆写他的两个方法 */
79 @Override /** 当被关闭时,执行这个方法 */
80 public void onDrawerClosed(View view) {
81 getActionBar().setTitle(mTitle);
82 invalidateOptionsMenu();
83 }
84 @Override /** 当被打开时,执行这个方法 */
85 public void onDrawerOpened(View drawerView) {
86 getActionBar().setTitle("请选择");
87 // 重绘菜单项的ActionBar。
88 // 当调用此方法的时候,它会自动调用一个方法:Call onPrepareOptionsMenu(所以要重写)。
89 invalidateOptionsMenu();
90 }
91 };
92 mDrawerLayout.setDrawerListener(mDrawerToggle);
93
94 if (savedInstanceState == null) {
95 selectItem(0);
96 }
97 }
98
99 @Override
100 public boolean onCreateOptionsMenu(Menu menu) {
101 MenuInflater inflater = getMenuInflater();
102 inflater.inflate(R.menu.main, menu);
103 return super.onCreateOptionsMenu(menu);
104 }
105
106 /* Called whenever we call invalidateOptionsMenu() */
107 @Override
108 public boolean onPrepareOptionsMenu(Menu menu) {
109 // 根据打开和关闭来实现右上角的图片显示。
110 boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); // 获取打开状态
111 menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
112 return super.onPrepareOptionsMenu(menu);
113 }
114
115 @Override
116 public boolean onOptionsItemSelected(MenuItem item) {
117 // 将ActionBar上的图标与Drawer结合起来。
118 // 点击左上角的图标,打开和关闭抽屉。
119 if (mDrawerToggle.onOptionsItemSelected(item)) {
120 return true;
121 }
122 switch (item.getItemId()) {
123 case R.id.action_websearch: // 右上角查询按钮
124 Intent intent = new Intent();
125 intent.setAction("android.intent.action.VIEW");
126 Uri uri = Uri.parse("http://www.baidu.com");
127 intent.setData(uri);
128 // catch event that there's no activity to handle intent
129 if (intent.resolveActivity(getPackageManager()) != null) {
130 startActivity(intent);
131 } else {
132 Toast.makeText(this, R.string.app_not_available,
133 Toast.LENGTH_LONG).show();
134 }
135 return true;
136 default:
137 return super.onOptionsItemSelected(item);
138 }
139 }
140
141 /* The click listner for ListView in the navigation drawer */
142 private class DrawerItemClickListener implements
143 ListView.OnItemClickListener {
144 @Override
145 public void onItemClick(AdapterView<?> parent, View view, int position,
146 long id) {
147 selectItem(position);
148 }
149 }
150
151 private void selectItem(int position) {
152 Fragment fragment = new PlanetFragment();
153 Bundle args = new Bundle();
154 // 传入参数
155 args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
156 fragment.setArguments(args);
157
158 FragmentManager fragmentManager = getFragmentManager();
159 fragmentManager.beginTransaction()
160 .replace(R.id.content_frame, fragment).commit();
161
162 // update selected item and title, then close the drawer
163 mDrawerList.setItemChecked(position, true);
164 setTitle(mPlanetTitles[position]);
165 mDrawerLayout.closeDrawer(mDrawerList);
166 }
167
168 @Override
169 public void setTitle(CharSequence title) {
170 mTitle = title;
171 getActionBar().setTitle(mTitle);
172 }
173
174 /**
175 * When using the ActionBarDrawerToggle, you must call it during
176 * onPostCreate() and onConfigurationChanged()...
177 */
178
179 @Override
180 protected void onPostCreate(Bundle savedInstanceState) {
181 super.onPostCreate(savedInstanceState);
182 // 需要将ActionDrawerToggle与DrawerLayout的状态同步。
183 // 将ActionBarDrawerToggle中的drawer图标,设置为ActionBar中的Home-Button的ICON。
184 mDrawerToggle.syncState(); // 实现同步即可。
185 }
186
187 @Override // 当屏幕旋转的时候调用。实现重新配置。
188 public void onConfigurationChanged(Configuration newConfig) {
189 super.onConfigurationChanged(newConfig);
190 // Pass any configuration change to the drawer toggls
191 mDrawerToggle.onConfigurationChanged(newConfig);
192 }
193
194 /**
195 * Fragment that appears in the "content_frame", shows a planet
196 */
197 public static class PlanetFragment extends Fragment {
198 public static final String ARG_PLANET_NUMBER = "planet_number";
199
200 public PlanetFragment() {
201 // Empty constructor required for fragment subclasses
202 }
203
204 @Override
205 public View onCreateView(LayoutInflater inflater, ViewGroup container,
206 Bundle savedInstanceState) {
207 View rootView = inflater.inflate(R.layout.fragment_planet,
208 container, false);
209 int i = getArguments().getInt(ARG_PLANET_NUMBER);
210 String planet = getResources()
211 .getStringArray(R.array.planets_array)[i];
212
213 int imageId = getResources().getIdentifier(
214 planet.toLowerCase(Locale.getDefault()), "drawable",
215 getActivity().getPackageName());
216 ((ImageView) rootView.findViewById(R.id.image))
217 .setImageResource(imageId);
218 getActivity().setTitle(planet);
219 return rootView;
220 }
221 }
222 }