編輯:關於 Android 程式設計
側滑顯示刪除按鈕是清單類 App 的標準互動,做法是自訂一組元件:一個負責攔截手勢的 ListView,加上一個可滑動的項目容器。整體效果如下。

這個類別負責判斷使用者的手勢是橫向滑動還是縱向捲動,並管理「同時只展開一個項目」的狀態。
public class DragDelListView extends ListView {
private boolean moveable = false;
private boolean closed = true;
private float mDownX, mDownY;
private int mTouchPosition, oldPosition = -1;
private DragDelItem mTouchView, oldView;
public DragDelListView(Context context) {
super(context);
}
public DragDelListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public DragDelListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
mTouchView = (DragDelItem) getChildAt(mTouchPosition - getFirstVisiblePosition());
mDownX = ev.getX();
mDownY = ev.getY();
if (oldPosition == mTouchPosition || closed) {
moveable = true;
mTouchView.mDownX = (int) mDownX;
} else {
moveable = false;
if (oldView != null) {
oldView.smoothCloseMenu(); // 自動收起上一個展開的項目
}
}
oldPosition = mTouchPosition;
oldView = mTouchView;
break;
case MotionEvent.ACTION_MOVE:
// 縱向位移明顯大於橫向,判定為捲動,交回父類處理
if (Math.abs(mDownX - ev.getX()) < Math.abs(mDownY - ev.getY()) * dp2px(2)) {
break;
}
if (moveable) {
int dis = (int) (mTouchView.mDownX - ev.getX());
if (mTouchView.state == mTouchView.STATE_OPEN) {
dis += mTouchView.mMenuView.getWidth();
}
mTouchView.swipe(dis);
ev.setAction(MotionEvent.ACTION_CANCEL);
}
break;
case MotionEvent.ACTION_UP:
if (moveable) {
// 滑過一半寬度就展開,否則收回
if ((mTouchView.mDownX - ev.getX()) > mTouchView.mMenuView.getWidth() / 2) {
mTouchView.smoothOpenMenu();
closed = false;
} else {
mTouchView.smoothCloseMenu();
closed = true;
}
ev.setAction(MotionEvent.ACTION_CANCEL);
}
break;
}
return super.onTouchEvent(ev);
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getContext().getResources().getDisplayMetrics());
}
}
兩個設計細節值得注意:用 ACTION_CANCEL 取代原本的 ACTION_UP/MOVE,可以阻止 ListView 誤觸發 click 事件;用「位移量是否超過菜單寬度一半」決定展開或收回,比固定門檻更符合操作直覺。
public class DragDelItem extends LinearLayout {
public static final int STATE_CLOSE = 0;
public static final int STATE_OPEN = 1;
private View mContentView;
public View mMenuView;
public int mDownX;
public int state = STATE_CLOSE;
private int mBaseX;
private Scroller scroll;
public DragDelItem(View contentView, View menuView) {
super(contentView.getContext());
scroll = new Scroller(getContext());
mContentView = contentView;
mMenuView = menuView;
setLayoutParams(new AbsListView.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
mContentView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mMenuView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mContentView);
addView(mMenuView);
}
/** 依位移量重新配置兩個子 View 的位置 */
public void swipe(int dis) {
if (dis > mMenuView.getWidth()) { dis = mMenuView.getWidth(); }
if (dis < 0) { dis = 0; }
mContentView.layout(-dis, mContentView.getTop(),
mContentView.getWidth() - dis, getMeasuredHeight());
mMenuView.layout(mContentView.getWidth() - dis, mMenuView.getTop(),
mContentView.getWidth() + mMenuView.getWidth() - dis,
mMenuView.getBottom());
}
@Override
public void computeScroll() {
if (state == STATE_OPEN) {
if (scroll.computeScrollOffset()) {
swipe(scroll.getCurrX());
postInvalidate();
}
} else {
if (scroll.computeScrollOffset()) {
swipe(mBaseX - scroll.getCurrX());
postInvalidate();
}
}
}
public void smoothCloseMenu() {
state = STATE_CLOSE;
mBaseX = -mContentView.getLeft();
scroll.startScroll(0, 0, mBaseX, 0, 350);
postInvalidate();
}
public void smoothOpenMenu() {
state = STATE_OPEN;
scroll.startScroll(-mContentView.getLeft(), 0, mMenuView.getWidth() / 2, 0, 350);
postInvalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mMenuView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
mContentView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// 內容 initially 佔滿寬度,菜單排在畫面右側之外
mContentView.layout(0, 0, getMeasuredWidth(), mContentView.getMeasuredHeight());
mMenuView.layout(getMeasuredWidth(), 0,
getMeasuredWidth() + mMenuView.getMeasuredWidth(),
mContentView.getMeasuredHeight());
}
}
這裡的關鍵是 Scroller 搭配 computeScroll():位置變化交給 Scroller 產生插值,再由 computeScroll() 每帧回呼 swipe() 重繪,就能得到平滑的動畫,而不必自己算時間曲線。
項目內容(swipecontent.xml):
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/rl_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#999999"
android:padding="8dp">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@+id/iv_icon"
android:text="name"
android:textColor="@android:color/black"
android:textSize="18sp" />
</RelativeLayout>
滑出的操作區(swipemenu.xml):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_open"
android:layout_width="90dp"
android:layout_height="match_parent"
android:gravity="center"
android:background="#C2C2C2"
android:text="置頂"
android:textColor="@android:color/white"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_del"
android:layout_width="90dp"
android:layout_height="match_parent"
android:gravity="center"
android:background="#FF0000"
android:text="刪除"
android:textColor="@android:color/white"
android:textSize="18sp" />
</LinearLayout>
Adapter 的核心是把兩個布局合成一個 DragDelItem 再交給 ListView:
public class MainActivity extends Activity {
private List<ApplicationInfo> mAppList;
private DragDelListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
mAppList = getPackageManager().getInstalledApplications(0);
mListView = (DragDelListView) findViewById(R.id.listView);
mListView.setAdapter(new AppAdapter(mAppList));
}
class AppAdapter extends BaseAdapter {
private List<ApplicationInfo> mAppList;
public AppAdapter(List<ApplicationInfo> appList) {
mAppList = appList;
}
@Override public int getCount() { return mAppList.size(); }
@Override public ApplicationInfo getItem(int position) { return mAppList.get(position); }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
View content = View.inflate(getApplicationContext(), R.layout.swipecontent, null);
View menu = View.inflate(getApplicationContext(), R.layout.swipemenu, null);
convertView = new DragDelItem(content, menu);
holder = new ViewHolder(convertView);
} else {
holder = (ViewHolder) convertView.getTag();
}
ApplicationInfo item = getItem(position);
holder.iv_icon.setImageDrawable(item.loadIcon(getPackageManager()));
holder.tv_name.setText(item.loadLabel(getPackageManager()));
holder.tv_open.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Toast.makeText(MainActivity.this, "置頂:" + position, Toast.LENGTH_SHORT).show();
}
});
holder.tv_del.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Toast.makeText(MainActivity.this, "刪除:" + position, Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
class ViewHolder {
ImageView iv_icon;
TextView tv_name, tv_open, tv_del;
RelativeLayout relativeLayout;
public ViewHolder(View view) {
iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
tv_name = (TextView) view.findViewById(R.id.tv_name);
tv_open = (TextView) view.findViewById(R.id.tv_open);
tv_del = (TextView) view.findViewById(R.id.tv_del);
relativeLayout = (RelativeLayout) view.findViewById(R.id.rl_layout);
// 讓內容區填滿扣除菜單寬度後的剩餘空間
WindowManager wm = (WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
relativeLayout.setMinimumWidth(width - 60);
view.setTag(this);
}
}
}
}
主界面布局:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.draglistview.DragDelListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
整個機制的核心只有三件事:在 onTouchEvent 中區分橫滑與直捲、在 swipe() 中重新 layout 兩個子 View、用 Scroller 讓位移帶有動畫。掌握這三點之後,要加上多個按鈕、改成 RecyclerView 版本、或替換成 ItemTouchHelper 官方方案,都只是換個骨架而已。
Android 最佳實踐:UI 開發從多螢幕適配到沉浸式體驗
這篇整理 Android 官方 UI 訓練指南的實作要點,從多螢幕適配一路談到自訂 View、向下相容與沉浸式全螢幕,適合當作專案開發時的對照清單。 一、支援多種螢幕尺
Android 平台 Camera 實時濾鏡實作探討(八):一個簡單的美顏濾鏡
美顏通常包含磨皮、美白、瘦臉等效果,其中磨皮演算法的討論已經很多,例如雙指數邊緣平滑濾波器、選擇性模糊、基於局部均方差相關資訊的圖像去噪、導向濾波磨皮、遞歸雙邊濾波磨皮等
Android Service 全面解析:分類、生命週期與使用方式
一、Service 的分類 依執行位置:本地服務與遠程服務 本地服務(Local)依附在主進程上,因此不必 IPC、也不用寫 AIDL,bindService 相對簡單,
Android 繪圖 API 總整理:Bitmap、Canvas、Paint、Path 一次搞懂
只要做過自訂控制項,就一定會跟這幾個傢伙打照面:Bitmap 負責裝圖,Canvas 負責畫布,Paint 負責畫筆,Path 負責軌跡。Android 在這塊提供的支援