編輯:關於 Android 程式設計
View 滑動是自定義控件的基礎,開發中也難免遇到。其實無論哪一種實現方式,基本思想都是類似的:當觸摸事件傳到 View 時,系統記下觸摸點的座標;手指移動時記下新的座標並算出偏移量;再透過偏移量修改 View 的座標。
差別只在於「修改座標」這一步用了哪個 API。本文說明六種做法:layout()、offsetLeftAndRight() 與 offsetTopAndBottom()、LayoutParams、動畫、scrollTo 與 scrollBy,以及 Scroller。屬性動畫的細節留待下一篇深入。
View 繪製時會呼叫 onLayout() 來設定顯示位置,因此我們也可以直接修改 left、top、right、bottom 這四個屬性來控制座標。
先自定義一個 View,在 onTouchEvent() 中取得觸摸點座標:
public boolean onTouchEvent(MotionEvent event) {
// 取得手指處的橫座標與縱座標
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
// ...
接著在 ACTION_MOVE 中計算偏移量,呼叫 layout() 重新擺放自己:
case MotionEvent.ACTION_MOVE:
// 計算移動的距離
int offsetX = x - lastX;
int offsetY = y - lastY;
// 呼叫 layout 方法重新放置它的位置
layout(getLeft() + offsetX, getTop() + offsetY,
getRight() + offsetX, getBottom() + offsetY);
break;
每次移動都呼叫 layout() 對自己重新佈局,達到移動效果。
完整程式碼(CustomView.java):
package com.example.liuwangshu.moonviewslide;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class CustomView extends View {
private int lastX;
private int lastY;
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context) {
super(context);
}
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
int offsetX = x - lastX;
int offsetY = y - lastY;
layout(getLeft() + offsetX, getTop() + offsetY,
getRight() + offsetX, getBottom() + offsetY);
break;
}
return true;
}
}
布局中引用:
<?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">
<com.example.liuwangshu.moonviewslide.CustomView
android:id="@+id/customview"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="50dp"
android:background="@android:color/holo_red_light" />
</LinearLayout>
實作提醒:ACTION_MOVE 中缺少 lastX = x 與 lastY = y 的更新,否則偏移量會以 ACTION_DOWN 的位置為基準不斷累加,導致 View 飛出螢幕。另外,layout() 只能由父容器呼叫,在 View 內部直接呼叫自己雖可運行,但並非官方推薦用法——它屬於 ViewGroup 的 API,實務上更常見的是搭配 offsetLeftAndRight 使用。
這兩個方法與 layout() 效果相近,使用更簡潔。把 ACTION_MOVE 中的程式碼換成:
case MotionEvent.ACTION_MOVE:
int offsetX = x - lastX;
int offsetY = y - lastY;
offsetLeftAndRight(offsetX); // 對 left 與 right 進行偏移
offsetTopAndBottom(offsetY); // 對 top 與 bottom 進行偏移
break;
它們的優勢在於只更新座標而不觸發重新佈局,效能上比 layout() 更好。
LayoutParams 保存著一個 View 的佈局參數,改動它同樣能達到移動效果:
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);
因為父容器是 LinearLayout,所以用 LinearLayout.LayoutParams;若父容器是 RelativeLayout 就要換成 RelativeLayout.LayoutParams。也可以用通用的 MarginLayoutParams:
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);
這種方式會觸發 requestLayout(),效能成本較高,適合移動頻率不高的場景。
用 View 動畫來移動。在 res 下新建 anim 目錄並建立 translate.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate
android:duration="1000"
android:fromXDelta="0"
android:toXDelta="300" />
</set>
Java 中引用:
mCustomView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.translate));
屬性動畫則更簡潔,讓 CustomView 在 1000 毫秒內沿 X 軸右移 300 像素:
ObjectAnimator.ofFloat(mCustomView, "translationX", 0, 300).setDuration(1000).start();
兩者的關鍵差異:View 動畫只改變繪製效果,View 的真正位置沒變,因此觸摸事件的回應區域仍在原處;屬性動畫改的是 translationX 這個真實屬性,事件命中區域會跟著移動。若需要「看起來動了、摸也摸得到」的效果,請用屬性動畫。
scrollTo(x, y) 移動到一個絕對座標,scrollBy(dx, dy) 則移動相對增量 dx、dy。scrollBy 最終也是呼叫 scrollTo 完成的。
需要特別理解的是:這兩個方法移動的是 View 的內容,而非 View 本身。在 ViewGroup 中使用時,移動的是它所有的子 View。因此,View 內容往某方向滾動,等價於 View 本身往反方向移動——這也是為什麼呼叫時要傳負值:
((View) getParent()).scrollBy(-offsetX, -offsetY);
另外,scrollX/scrollY 的值恆為非正數(只能往左上方滾動),超出內容範圍的滾動會被系統約束,這些特性在實作時都要納入考量。
scrollTo/scrollBy 的缺點是瞬間完成,使用者體驗不佳。Scroller 能實現帶過渡效果的滑動——這個過程不是瞬間完成,而是在一段時間內逐步推進。
但要注意:Scroller 本身不能實現 View 滑動,它需要搭配 View 的 computeScroll() 才能產生彈性滑動效果。
以下實現 CustomView 平滑右移。
首先初始化 Scroller:
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
接著覆寫 computeScroll()。系統在繪製 View 時會於 draw() 中呼叫這個方法;我們在其中呼叫 scrollTo(),並透過 Scroller 不斷取得目前的捲動值,每移動一小段就呼叫 invalidate() 觸發重繪,重繪又會呼叫 computeScroll(),形成連續的平滑移動:
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
}
// 透過不斷重繪,不斷呼叫 computeScroll
invalidate();
}
然後呼叫 Scroller.startScroll()。在 CustomView 中寫一個 smoothScrollTo(),於 2000 毫秒內沿 X 軸平移 delta 像素:
public void smoothScrollTo(int destX, int destY) {
int scrollX = getScrollX();
int delta = destX - scrollX;
// 2000 毫秒內滑向 destX
mScroller.startScroll(scrollX, 0, delta, 0, 2000);
invalidate();
}
在 Activity 中呼叫:
// 使用 Scroller 進行平滑移動
mCustomView.smoothScrollTo(-400, 0);
這裡設定 CustomView 沿 X 軸向右平移 400 像素(因為 scrollTo 傳負值代表內容右移,所以目標值是 -400)。
這段程式碼有個值得修正的細節:invalidate() 被放在 if 之外,導致動畫結束後仍會持續重繪,形成無意義的空轉。應改為只在 computeScrollOffset() 回傳 true 時才呼叫 invalidate(),讓迴圈在動畫完成後自然停止。
layout():會觸發重新佈局,效能較差,且屬於父容器的 API,不建議在 View 內部使用。
offsetLeftAndRight / offsetTopAndBottom:只更新座標,不觸發 layout,是這六種中位移類操作裡效能最好的。
LayoutParams:直觀易懂,但 setLayoutParams 會觸發 requestLayout,頻率高時需注意。
View 動畫:只改視覺,不改真實位置,事件區域不跟著動。
scrollTo / scrollBy:移動的是內容而非 View 本身,且只能往左上方捲動,需要搭配座標換算。
Scroller:不是位移手段,而是為 scrollTo 提供時間軸,實現平滑過渡。
實務上的常見組合是:用 Scroller 驅動時間軸,在 computeScroll 中呼叫 scrollTo 完成位移。這也是各類「平滑滾動到目標位置」效果背後的標準做法。
仿微信語音對講:自定義錄音按鈕與策略模式解耦實作
微信的「按住說話」幾乎成了語音輸入的標準交互。它其實不難實現,核心就是一個自定義 Button 攔截觸摸事件,加上一個背景服務等級的錄音流程。本文把這個按鈕封裝成獨立控制
Android 應用《撕開美女衣服》的實現原理與源代碼解析
現在很多 Android 應用市場中都能找到這類趣味小應用,比如「撕開美女衣服」「吹裙子」等,它們的下載量往往相當可觀。作為 Android 開發人員或技術人員,我們不能
藍牙防丟器原理與 Android BLE 開發實踐
本文整理自一個已完成的藍牙防丟器專案,重點說明原理、產品實現,以及 Android 端的 BLE 介面編程方式。至於 BLE 協定本身與涉及 JNI 的內部源碼實現,留待
Android 瀑布流照片牆實作:讓不規則排列展現獨特美感
傳統的介面排版總是行列分明、井然有序,看久了難免讓人生出幾分審美疲勞。就在這個時候,瀑布流布局憑藉它看似隨性、實則別有韻味的排列方式,為使用者帶來耳目一新的感受,也難怪有