編輯:關於 Android 程式設計
這一節是基礎 UI 控制項的最後一位:DrawerLayout,官方提供的側滑選單控制項。它和上一節的 ViewPager 一樣是 3.0 之後才加入的,低版本要使用得引入 v4 支援包。
提到側滑,很多人第一時間想到 GitHub 上的 SlidingMenu。不過那個專案有兩個版本,其中一個還得依賴 ActionBarSherlock。既然 Google 官方已經提供了現成的控制項,沒道理不用——而且在 Material Design 規範裡到處可見的側滑動畫,大多能靠 Toolbar 搭配 DrawerLayout 完成。也有人喜歡把它叫做「抽屜控制項」。
1. 主內容檢視必須是 DrawerLayout 的第一個子檢視。
2. 主內容檢視的寬高要設成 match_parent。
3. 必須明確指定側滑檢視的 android:layout_gravity。
layout_gravity="start" 表示由左側滑出,"end" 表示由右側滑出。不建議使用 left 與 right,因為它們不支援 RTL 版面。
側滑檢視的寬度以 dp 計,建議不要超過 320dp,這樣使用者永遠能看到一部分主內容,知道選單還可以關掉。
手勢監聽透過 mDrawerLayout.setDrawerListener(...) 設定。若要搭配 ActionBar,讓使用者點擊應用圖示時彈出選單,則需要 ActionBarDrawerToggle——它是 DrawerLayout.DrawerListener 的實作類,可以覆寫 onDrawerOpened() 與 onDrawerClosed() 來監聽抽屜的拉出與隱藏。這裡不展開,因為 5.0 之後我們用的是 Toolbar。
執行結果:

activity_main.xml——最外層一定要是 DrawerLayout:
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
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" />
</FrameLayout>
ListView 的項目版面與資料類很單純,這裡略過。Adapter 直接複用先前寫過的可複用 MyAdapter。
fg_content.xml:
<!--?xml version=1.0 encoding=utf-8?-->
<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>
ContentFragment.java:
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 = (TextView) view.findViewById(R.id.tv_content);
String text = getArguments().getString("text");
tv_content.setText(text);
return view;
}
}
MainActivity.java:
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 = (DrawerLayout) findViewById(R.id.drawer_layout);
list_left_drawer = (ListView) findViewById(R.id.list_left_drawer);
menuLists = new ArrayList<Item>();
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);
}
}
逻辑就是點選項目 → 換掉中間的 Fragment → 順手把抽屜關上。
從上面的結構其實已經能看出來,DrawerLayout 最多由三部分組成:中間的內容、左側選單、右側選單。下面做一個雙側滑的版本。
執行結果:

先準備左右兩個 Fragment 及其版面。
左側:fg_left.xml(一張圖,點擊後跳到新 Activity)
<!--?xml version=1.0 encoding=utf-8?-->
<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>
LeftFragment.java:
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 = (ImageView) 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;
}
}
右側:fg_right.xml(三個按鈕,點擊後替換中間的 Fragment)
<!--?xml version=1.0 encoding=utf-8?-->
<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>
RightFragment.java:
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("點擊了右側選單項一", R.color.blue)).commit();
drawer_layout.closeDrawer(Gravity.END);
break;
case R.id.btn_two:
fManager.beginTransaction().replace(R.id.fly_content,
new ContentFragment("點擊了右側選單項二", R.color.red)).commit();
drawer_layout.closeDrawer(Gravity.END);
break;
case R.id.btn_three:
fManager.beginTransaction().replace(R.id.fly_content,
new ContentFragment("點擊了右側選單項三", R.color.yellow)).commit();
drawer_layout.closeDrawer(Gravity.END);
break;
}
}
public void setDrawerLayout(DrawerLayout drawer_layout) {
this.drawer_layout = drawer_layout;
}
}
中間的 ContentFragment.java:
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 = (TextView) view.findViewById(R.id.tv_content);
tv_content.setText(strContent);
return view;
}
}
接著做一個頂部橫欄。
view_topbar.xml:
<!--?xml version=1.0 encoding=utf-8?-->
<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>
activity_main.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
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" />
<fragment
android:id="@+id/fg_left_menu"
android:name="jay.com.drawerlayoutdemo2.LeftFragment"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="@layout/fg_left" />
<fragment
android:id="@+id/fg_right_menu"
android:name="jay.com.drawerlayoutdemo2.RightFragment"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_gravity="end"
tools:layout="@layout/fg_right" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DrawerLayout drawer_layout;
private View topbar;
private Button btn_right;
private RightFragment fg_right_menu;
private LeftFragment fg_left_menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager 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 = (DrawerLayout) findViewById(R.id.drawer_layout);
topbar = findViewById(R.id.topbar);
btn_right = (Button) 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 drawerView) { }
@Override public void onDrawerClosed(View drawerView) {
// 關閉後重新上鎖
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. openDrawer(Gravity.END):決定打開哪一側,START 是左、END 是右。
2. 鎖定與解鎖的時機:setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED, Gravity.END) 會讓該側選單無法用手勢開關,只能呼叫 openDrawer();LOCK_MODE_UNLOCKED 則解除這個限制。本例的做法是:進場先鎖、點按鈕時解鎖並打開、關閉後再鎖回去。這樣能避免使用者在內容還沒準備好時誤觸滑出選單。
3. 版面中的 tag 屬性:本例沒用到。若要在 onDrawerSlide() 裡分辨是哪一側觸發的事件,可以用它的第一個參數 drawerView 呼叫 drawerView.getTag() 來判斷,再做對應處理。
DrawerLayout 的價值在於它把「抽屜」這種互動抽象成了標準元件,我們只要專心填內容、處理點擊,滑動手勢、遮罩、邊緣陰影都交給框架。要記住的三條鐵律:主內容擺第一且填滿、側滑檢視一定要設 layout_gravity、寬度別超過 320dp。
Calabash-Android 上手實作:從截圖到自訂步驟
前一篇說明了如何在 Windows 環境中架好 calabash-android 的測試環境,這篇用一個實例帶大家跑一遍它的基本用法。 範例專案取自:https://gi
只用一個 TextView 實作高仿京東淘寶的活動倒計時
今天要分享的是:僅僅使用一個 TextView,就能做出高仿京東、淘寶、唯品會等電商 App 的活動倒計時樣式。 為什麼要只用一個 TextView 最近公司在做效
用 Canvas 與屬性動畫製作萌蠢小鬼
自訂 View 的起點 想畫出一個會動的小鬼,可以先建立一個繼承 View 的 GhostView,再把角色拆成頭、眼睛、身體與影子,逐步完成。 測量與影子 自訂 V
近期流行的 Android 短信蠕蟲病毒:原理拆解與防範建議
最近一種手機病毒集中爆發,傳播短信的形式大致是: 「XXX(機主姓名)看這個,ht://********XXshenqi.apk」 短信開頭用的是發送者通訊錄裡存的聯繫人