編輯:關於 Android 程式設計
側滑導航欄幾乎是每個 App 的標配,QQ、微信之類的應用更是把它玩到了極致。本文把自己手刻的實現完整攤開來講,適合想真正搞懂原理、而不是只會複製官方庫的讀者。

介面確實樸素,但結構清晰,後面換上設計稿裡的圖片就是像樣的成品了。
核心是一個自訂的 DragLayout(繼承 FrameLayout),裡面裝三層東西:左側菜單、主內容、以及一層可選的陰影。拖拽能力交給 support-v4 的 ViewDragHelper,手勢方向判斷交給 GestureDetectorCompat,兩者搭配才能兼顧「橫向拖菜單」與「縱向滾列表」不打架。
<cn.edu.rjxy.activity.DragLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/dl"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg1"
android:clickable="true"
android:orientation="vertical" >
<!-- 左側菜單頁面 -->
<include layout="@layout/leftmenu" />
<cn.edu.rjxy.activity.MyRelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#eeeeee"
android:orientation="vertical" >
<include layout="@layout/middleview" />
</cn.edu.rjxy.activity.MyRelativeLayout>
</cn.edu.rjxy.activity.DragLayout>
<?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"
android:paddingBottom="30dp"
android:paddingLeft="30dp"
android:paddingTop="10dp" >
<LinearLayout
android:id="@+id/menu_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left|center"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="@+id/iv_headimage"
android:layout_width="55dp"
android:layout_height="55dp"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|left"
android:layout_marginLeft="6dp"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_sname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="員工名"
android:textColor="#ffffff"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:textColor="#ffffff"
android:text="蝴蝶為花醉,花卻隨風飛,花舞花落淚,花哭花瓣飛"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/tv_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="設置"
android:drawablePadding="5dp"
android:gravity="center"
android:drawableLeft="@drawable/ic_launcher"
android:textColor="#ffffff"
android:textSize="15sp" />
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/tv_setting"
android:layout_below="@id/menu_header"
android:layout_marginBottom="30dp"
android:layout_marginTop="20dp"
android:cacheColorHint="#00000000"
android:divider="@null"
android:scrollbars="none"
android:textColor="#ffffff" />
</RelativeLayout>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:orientation="horizontal" >
<ImageView
android:id="@+id/menu_imageView1"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/menu_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:gravity="center_vertical"
android:text="菜單1"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#00C5CD"
android:orientation="horizontal" >
<ImageButton
android:id="@+id/menu_imgbtn"
android:layout_width="20dp"
android:layout_height="15dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="1dp"
android:background="@drawable/leftmenu_btn_selector" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/app_name"
android:textColor="@android:color/white"
android:textSize="20dp" />
</RelativeLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/leftmenu_btn_press" android:state_pressed="true"/>
<item android:drawable="@drawable/leftmenu_btn" android:state_pressed="false"/>
</selector>
這個類的職責很單一:當菜單不是關閉狀態時,把觸摸事件全部截住,抬手時順手關掉菜單,避免使用者誤觸底層按鈕。
package cn.edu.rjxy.activity;
import cn.edu.rjxy.activity.DragLayout.Status;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class MyRelativeLayout extends LinearLayout {
private DragLayout dl;
public MyRelativeLayout(Context context) {
super(context);
}
public MyRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setDragLayout(DragLayout dl) {
this.dl = dl;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (dl.getStatus() != Status.Close) {
return true;
}
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (dl.getStatus() != Status.Close) {
if (event.getAction() == MotionEvent.ACTION_UP) {
dl.close();
}
return true;
}
return super.onTouchEvent(event);
}
}
幾個值得留意的設計點:
YScrollDetector 只在「橫向位移大於縱向位移」時判定為橫滑,解決手勢衝突。clampViewPositionHorizontal() 把主內容的位移鎖在 0 ~ range(寬度的 60%)之間。onViewReleased() 依拋擲速度與拖動距離決定吸附到開或關。animateView() 透過 nineoldandroids 的 ViewHelper 同步做縮放、位移、透明度與背景色漸變,這是「層次感」的來源。
package cn.edu.rjxy.activity;
import com.nineoldandroids.view.ViewHelper;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class DragLayout extends FrameLayout {
private boolean isShowShadow = true;
private GestureDetectorCompat gestureDetector;
private ViewDragHelper dragHelper;
private DragListener dragListener;
private int range;
private int width;
private int height;
private int mainLeft;
private Context context;
private ImageView iv_shadow;
private RelativeLayout vg_left;
private MyRelativeLayout vg_main;
private Status status = Status.Close;
public DragLayout(Context context) {
this(context, null);
}
public DragLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
this.context = context;
}
public DragLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
gestureDetector = new GestureDetectorCompat(context, new YScrollDetector());
dragHelper = ViewDragHelper.create(this, dragHelperCallback);
}
class YScrollDetector extends SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) {
// 只有橫向位移佔主導才算橫滑
return Math.abs(dy) <= Math.abs(dx);
}
}
private ViewDragHelper.Callback dragHelperCallback = new ViewDragHelper.Callback() {
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
if (mainLeft + dx < 0) {
return 0;
} else if (mainLeft + dx > range) {
return range;
} else {
return left;
}
}
@Override
public boolean tryCaptureView(View child, int pointerId) {
return true;
}
@Override
public int getViewHorizontalDragRange(View child) {
return width;
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
super.onViewReleased(releasedChild, xvel, yvel);
if (xvel > 0) {
open();
} else if (xvel < 0) {
close();
} else if (releasedChild == vg_main && mainLeft > range * 0.3) {
open();
} else if (releasedChild == vg_left && mainLeft > range * 0.7) {
open();
} else {
close();
}
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
if (changedView == vg_main) {
mainLeft = left;
} else {
mainLeft = mainLeft + left;
}
if (mainLeft < 0) {
mainLeft = 0;
} else if (mainLeft > range) {
mainLeft = range;
}
if (isShowShadow) {
iv_shadow.layout(mainLeft, 0, mainLeft + width, height);
}
if (changedView == vg_left) {
vg_left.layout(0, 0, width, height);
vg_main.layout(mainLeft, 0, mainLeft + width, height);
}
dispatchDragEvent(mainLeft);
}
};
public interface DragListener {
public void onOpen();
public void onClose();
public void onDrag(float percent);
}
public void setDragListener(DragListener dragListener) {
this.dragListener = dragListener;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (isShowShadow) {
iv_shadow = new ImageView(context);
iv_shadow.setImageResource(R.drawable.shadow);
LayoutParams lp = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
addView(iv_shadow, 1, lp);
}
vg_left = (RelativeLayout) getChildAt(0);
vg_main = (MyRelativeLayout) getChildAt(isShowShadow ? 2 : 1);
vg_main.setDragLayout(this);
vg_left.setClickable(true);
vg_main.setClickable(true);
}
public ViewGroup getVg_main() {
return vg_main;
}
public ViewGroup getVg_left() {
return vg_left;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = vg_left.getMeasuredWidth();
height = vg_left.getMeasuredHeight();
range = (int) (width * 0.6f);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
vg_left.layout(0, 0, width, height);
vg_main.layout(mainLeft, 0, mainLeft + width, height);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return dragHelper.shouldInterceptTouchEvent(ev) && gestureDetector.onTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
try {
dragHelper.processTouchEvent(e);
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
private void dispatchDragEvent(int mainLeft) {
if (dragListener == null) {
return;
}
float percent = mainLeft / (float) range;
animateView(percent);
dragListener.onDrag(percent);
Status lastStatus = status;
if (lastStatus != getStatus() && status == Status.Close) {
dragListener.onClose();
} else if (lastStatus != getStatus() && status == Status.Open) {
dragListener.onOpen();
}
}
private void animateView(float percent) {
float f1 = 1 - percent * 0.3f;
ViewHelper.setScaleX(vg_main, f1);
ViewHelper.setScaleY(vg_main, f1);
ViewHelper.setTranslationX(vg_left,
-vg_left.getWidth() / 2.3f + vg_left.getWidth() / 2.3f * percent);
ViewHelper.setScaleX(vg_left, 0.5f + 0.5f * percent);
ViewHelper.setScaleY(vg_left, 0.5f + 0.5f * percent);
ViewHelper.setAlpha(vg_left, percent);
if (isShowShadow) {
ViewHelper.setScaleX(iv_shadow, f1 * 1.4f * (1 - percent * 0.12f));
ViewHelper.setScaleY(iv_shadow, f1 * 1.85f * (1 - percent * 0.12f));
}
getBackground().setColorFilter(
evaluate(percent, Color.BLACK, Color.TRANSPARENT), Mode.SRC_OVER);
}
private Integer evaluate(float fraction, Object startValue, Integer endValue) {
int startInt = (Integer) startValue;
int startA = (startInt >> 24) & 0xff;
int startR = (startInt >> 16) & 0xff;
int startG = (startInt >> 8) & 0xff;
int startB = startInt & 0xff;
int endInt = (Integer) endValue;
int endA = (endInt >> 24) & 0xff;
int endR = (endInt >> 16) & 0xff;
int endG = (endInt >> 8) & 0xff;
int endB = endInt & 0xff;
return (int) ((startA + (int) (fraction * (endA - startA))) << 24)
| (int) ((startR + (int) (fraction * (endR - startR))) << 16)
| (int) ((startG + (int) (fraction * (endG - startG))) << 8)
| (int) ((startB + (int) (fraction * (endB - startB))));
}
@Override
public void computeScroll() {
if (dragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
public enum Status { Drag, Open, Close }
public Status getStatus() {
if (mainLeft == 0) {
status = Status.Close;
} else if (mainLeft == range) {
status = Status.Open;
} else {
status = Status.Drag;
}
return status;
}
public void open() {
open(true);
}
public void open(boolean animate) {
if (animate) {
if (dragHelper.smoothSlideViewTo(vg_main, range, 0)) {
ViewCompat.postInvalidateOnAnimation(this);
}
} else {
vg_main.layout(range, 0, range * 2, height);
dispatchDragEvent(range);
}
}
public void close() {
close(true);
}
public void close(boolean animate) {
if (animate) {
if (dragHelper.smoothSlideViewTo(vg_main, 0, 0)) {
ViewCompat.postInvalidateOnAnimation(this);
}
} else {
vg_main.layout(0, 0, width, height);
dispatchDragEvent(0);
}
}
}
要注意的是,若希望其他頁面也有同樣的側滑效果,做法就是把該頁內容同樣包進 DragLayout + MyRelativeLayout,然後重複一遍初始化流程。
package cn.edu.rjxy.activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.edu.rjxy.activity.DragLayout.DragListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** 左側側滑菜單 */
private DragLayout mDragLayout;
private ListView menuListView; // 菜單列表
private ImageButton menuSettingBtn; // 呼出菜單的按鈕
private LinearLayout menu_header;
private TextView menu_setting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_setting = (TextView) this.findViewById(R.id.tv_setting);
menu_header = (LinearLayout) this.findViewById(R.id.menu_header);
mDragLayout = (DragLayout) findViewById(R.id.dl);
mDragLayout.setDragListener(new DragListener() {
@Override public void onOpen() {}
@Override public void onClose() {}
@Override public void onDrag(float percent) {}
});
List<Map<String, Object>> data = getMenuData();
menuListView = (ListView) findViewById(R.id.lv);
menuListView.setAdapter(new SimpleAdapter(this, data,
R.layout.menulist_item_text,
new String[] { "item", "image" },
new int[] { R.id.menu_text, R.id.menu_imageView1 }));
menuSettingBtn = (ImageButton) findViewById(R.id.menu_imgbtn);
menuSettingBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDragLayout.open();
}
});
initResideListener();
}
private void initResideListener() {
// 點擊個人中心
menu_header.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "進入個人中心界面", Toast.LENGTH_LONG).show();
}
});
// 點擊子菜單項
menuListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: Toast.makeText(MainActivity.this, "0", Toast.LENGTH_LONG).show(); break;
case 1: Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show(); break;
case 2: Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show(); break;
case 3: Toast.makeText(MainActivity.this, "3", Toast.LENGTH_LONG).show(); break;
case 4: Toast.makeText(MainActivity.this, "4", Toast.LENGTH_LONG).show(); break;
case 5: Toast.makeText(MainActivity.this, "5", Toast.LENGTH_LONG).show(); break;
default: break;
}
}
});
// 進入設置
menu_setting.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "進入設置界面", Toast.LENGTH_LONG).show();
}
});
}
private List<Map<String, Object>> getMenuData() {
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
String[] titles = { "需參加會議", "已參加會議", "個人信息完善", "密碼修改" };
for (String t : titles) {
Map<String, Object> item = new HashMap<String, Object>();
item.put("item", t);
item.put("image", R.drawable.ic_launcher);
data.add(item);
}
return data;
}
}
整套實作的關鍵其實只有一句話:把「拖動」與「手勢方向判斷」分開處理,剩下的縮放與漸變都是表現層的調味料。理解了這點,替換成官方 DrawerLayout 或改造成右滑菜單都很輕鬆。
Android PopupWindow 實作:多層級聯動篩選選單
在不少列表頁與搜尋場景裡,我們會看到「一級選單切換、二級選項連動更新」的篩選設計。本文以 PopupWindow 搭配雙 ListView 為基礎,示範如何打造這樣一個層
Android 應用架構搭建實錄:從 MVC 走向 MVP 的分層設計
一、前言:為什麼要重新搭一次框架 Android 團隊普遍規模不大,架構的重要性在很多公司並不明顯;加上開源框架層出不窮,上手一個專案的成本被壓得很低。但這不代表架構不重
Android 插件化實作:用 DexClassLoader 與 AssetManager 啟動插件 Activity
在 Android 應用中,並非所有功能都必須預先安裝。透過動態載入外掛 APK 或 ZIP 檔,可以在不安裝系統應用程式的情況下擴充主程式能力。這篇文章說明如何以 De
自定義 Dialog 中的 EditText 無法彈出鍵盤,問題出在這裡
最近我獨立開發的專案《全醫會》已經進入內測階段,很快會上架各大應用市場。之前做的幾個專案因為種種原因最終沒能上架,一直是我的遺憾,所以這次心情格外好。 目前在進行一個新專