編輯:關於 Android 程式設計
本節是基礎 UI 控件系列的最後一個:DrawerLayout,官方提供的側滑菜單控件。和 ViewPager 一樣在 3.0 之後引入,低版本要使用得靠 v4 相容包。既然 Google 已經把輪子造好了,沒理由不用。而且在 Material Design 設計規範裡,到處可見的側滑菜單動畫效果,大多都能用 Toolbar + DrawerLayout 組合出來。也有人喜歡叫它「抽屜控件」。
DrawerLayout 的第一個子視圖。match_parent。android:layout_gravity:start 表示從左側滑出,end 表示從右側滑出。不建議使用 left 和 right。設置側滑事件監聽:mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() { ... });
另外它可以搭配 ActionBar 使用:使用者點擊 ActionBar 上的應用圖標時彈出側滑菜單,這要透過 ActionBarDrawerToggle(它是 DrawerLayout.DrawerListener 的實作類)來完成,覆寫 onDrawerOpened() 和 onDrawerClosed() 就能監聽抽屜的拉出與隱藏。不過 5.0 之後我們改用 Toolbar,這裡不展開,有興趣可以自行查閱文檔。

主佈局,注意最外層必須是 DrawerLayout:
<android.support.v4.widget.DrawerLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/ly_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="@+id/list_left_drawer"
android:layout_width="180dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#080808"
android:choiceMode="singleChoice"
android:divider="#FFFFFF"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
中間的 Fragment 佈局:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp" />
</RelativeLayout>
public class ContentFragment extends Fragment {
private TextView tv_content;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_content, container, false);
tv_content = view.findViewById(R.id.tv_content);
tv_content.setText(getArguments().getString("text"));
return view;
}
}
Activity 部分,Adapter 直接複用此前寫過的通用 MyAdapter:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DrawerLayout drawer_layout;
private ListView list_left_drawer;
private ArrayList<Item> menuLists;
private MyAdapter<Item> myAdapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer_layout = findViewById(R.id.drawer_layout);
list_left_drawer = findViewById(R.id.list_left_drawer);
menuLists = new ArrayList<>();
menuLists.add(new Item(R.mipmap.iv_menu_realtime, "實時信息"));
menuLists.add(new Item(R.mipmap.iv_menu_alert, "提醒通知"));
menuLists.add(new Item(R.mipmap.iv_menu_trace, "活動路線"));
menuLists.add(new Item(R.mipmap.iv_menu_settings, "相關設置"));
myAdapter = new MyAdapter<Item>(menuLists, R.layout.item_list) {
@Override
public void bindView(ViewHolder holder, Item obj) {
holder.setImageResource(R.id.img_icon, obj.getIconId());
holder.setText(R.id.txt_content, obj.getIconName());
}
};
list_left_drawer.setAdapter(myAdapter);
list_left_drawer.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ContentFragment contentFragment = new ContentFragment();
Bundle args = new Bundle();
args.putString("text", menuLists.get(position).getIconName());
contentFragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.ly_content, contentFragment)
.commit();
drawer_layout.closeDrawer(list_left_drawer);
}
}
代碼很直白,選中菜單項後替換中間內容,順手把抽屜關掉。
從上面的佈局大概能猜到,DrawerLayout 最多由三部分組成:中間的內容區、左側菜單、右側菜單。

左側 Fragment,這裡只放了一張圖,點擊後跳轉新頁面:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/img_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/bg_menu_left" />
</LinearLayout>
public class LeftFragment extends Fragment {
private DrawerLayout drawer_layout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_left, container, false);
ImageView img_bg = view.findViewById(R.id.img_bg);
img_bg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().startActivity(new Intent(getActivity(), OtherActivity.class));
drawer_layout.closeDrawer(Gravity.START);
}
});
return view;
}
/** 由 Activity 注入 DrawerLayout,點擊後才能關掉抽屜 */
public void setDrawerLayout(DrawerLayout drawer_layout) {
this.drawer_layout = drawer_layout;
}
}
右側 Fragment,三個按鈕,點擊後替換中間內容並關閉抽屜:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#2F9AF2"
android:gravity="center"
android:orientation="vertical">
<Button android:id="@+id/btn_one" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="菜單項一" />
<Button android:id="@+id/btn_two" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="菜單項二" />
<Button android:id="@+id/btn_three" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="菜單項三" />
</LinearLayout>
public class RightFragment extends Fragment implements View.OnClickListener {
private DrawerLayout drawer_layout;
private FragmentManager fManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_right, container, false);
view.findViewById(R.id.btn_one).setOnClickListener(this);
view.findViewById(R.id.btn_two).setOnClickListener(this);
view.findViewById(R.id.btn_three).setOnClickListener(this);
fManager = getActivity().getSupportFragmentManager();
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_one:
fManager.beginTransaction()
.replace(R.id.fly_content, new ContentFragment("1.點擊了右側菜單項一", R.color.blue))
.commit();
drawer_layout.closeDrawer(Gravity.END);
break;
case R.id.btn_two:
fManager.beginTransaction()
.replace(R.id.fly_content, new ContentFragment("2.點擊了右側菜單項二", R.color.red))
.commit();
drawer_layout.closeDrawer(Gravity.END);
break;
case R.id.btn_three:
fManager.beginTransaction()
.replace(R.id.fly_content, new ContentFragment("3.點擊了右側菜單項三", R.color.yellow))
.commit();
drawer_layout.closeDrawer(Gravity.END);
break;
}
}
public void setDrawerLayout(DrawerLayout drawer_layout) {
this.drawer_layout = drawer_layout;
}
}
中間內容的 Fragment 支持帶文字與背景色的構造:
public class ContentFragment extends Fragment {
private TextView tv_content;
private String strContent;
private int bgColor;
public ContentFragment(String strContent, int bgColor) {
this.strContent = strContent;
this.bgColor = bgColor;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_content, container, false);
view.setBackgroundColor(getResources().getColor(bgColor));
tv_content = view.findViewById(R.id.tv_content);
tv_content.setText(strContent);
return view;
}
}
頂欄佈局:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#DCDEDB">
<Button
android:id="@+id/btn_right"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/btn_selctor" />
</RelativeLayout>
主佈局:
<android.support.v4.widget.DrawerLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/topbar"
layout="@layout/view_topbar"
android:layout_width="wrap_content"
android:layout_height="48dp" />
<FrameLayout
android:id="@+id/fly_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="@+id/fg_left_menu"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="eliot.wakfo.com.anroid_drawerlayout.LeftFragment"
android:tag="LEFT"
tools:layout="@layout/fg_left" />
<fragment
android:id="@+id/fg_right_menu"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:name="eliot.wakfo.com.anroid_drawerlayout.LeftFragment"
android:tag="RIGHT"
tools:layout="@layout/fg_right" />
</android.support.v4.widget.DrawerLayout>
Activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DrawerLayout drawer_layout;
private FrameLayout fly_content;
private View topbar;
private Button btn_right;
private RightFragment fg_right_menu;
private LeftFragment fg_left_menu;
private FragmentManager fManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fManager = getSupportFragmentManager();
fg_right_menu = (RightFragment) fManager.findFragmentById(R.id.fg_right_menu);
fg_left_menu = (LeftFragment) fManager.findFragmentById(R.id.fg_left_menu);
initViews();
}
private void initViews() {
drawer_layout = findViewById(R.id.drawer_layout);
fly_content = findViewById(R.id.fly_content);
topbar = findViewById(R.id.topbar);
btn_right = topbar.findViewById(R.id.btn_right);
btn_right.setOnClickListener(this);
// 右側菜單鎖定,只能透過程式碼打開
drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
drawer_layout.setDrawerListener(new DrawerLayout.DrawerListener() {
@Override public void onDrawerSlide(View view, float slideOffset) {}
@Override public void onDrawerOpened(View view) {}
@Override public void onDrawerClosed(View view) {
// 關閉後再次鎖定
drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
}
@Override public void onDrawerStateChanged(int newState) {}
});
fg_right_menu.setDrawerLayout(drawer_layout);
fg_left_menu.setDrawerLayout(drawer_layout);
}
@Override
public void onClick(View v) {
drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END); // 解鎖
drawer_layout.openDrawer(Gravity.END);
}
}
1. drawer_layout.openDrawer(Gravity.END);
這句決定打開哪一個菜單,Gravity.START 代表左邊,Gravity.END 代表右邊。
2. 鎖定與解鎖的時序setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END) 會鎖定右側菜單,手勢無法開關,只能調 openDrawer();接著用 LOCK_MODE_UNLOCKED 解除鎖定,手勢就能正常關閉;最後在 onDrawerClosed() 裡再次鎖定,形成一個閉環。這個「解鎖 → 打開 → 關閉後重新鎖定」的組合,是實現「右側菜單只能由按鈕觸發」的標準做法。
3. 佈局中 android:tag 有什麼用?
上面沒實際用到,但在覆寫 onDrawerSlide() 時,可以透過第一個參數 drawerView 調用 drawerView.getTag().equals("LEFT") 判斷是哪個菜單觸發的事件,再分別處理。
線上搜索 Android 源代碼的實用方法
在 Google 缺席的年代,程序員遇到問題唯一的出路就是讀源碼。如今搜尋引擎能解決大部分開發問題,但若想真正理解某個 API 的內部運行機制,最終還是得回到源碼本身。
Activity 完全解析(二):setContentView 與 layout 的 inflate 過程
上一篇我們探討了 Activity 的啟動,從 startActivity() 到進程創建,再到 Activity 的創建,最後調用 onCreate() 方法。本篇我們
VIVO X5Pro 官方線刷包下載與刷機教學
不少網友對 VIVO X5Pro 的評價是:外觀漂亮、手感舒適、音色音質出眾。不知你對 VIVO X5Pro 又有什麼特別的看法呢?它是否是一款性價比不錯的手機?今天,筆
Android 沉浸式狀態列的另外兩種思路(含側滑與輸入法相容)
沉浸式狀態列並不新鮮,iOS 很早就有,Android 5.0 起也支援替狀態列上色。但由於一段時間內主流版本仍停留在 4.4,網路上常見的相容做法都是依賴「把狀態列變透