編輯:關於 Android 開發
View 的滑動是實現自定義控件的基礎,開發中也經常需要處理滑動。其實無論哪一種方式,基本思想都類似:當觸摸事件傳到 View 時,系統記錄觸摸點座標;手指移動時記錄移動後的座標並算出偏移量,再透過偏移量修改 View 的座標。
本文介紹六種滑動方法:layout()、offsetLeftAndRight() 與 offsetTopAndBottom()、LayoutParams、動畫、scrollTo 與 scrollBy,以及 Scroller。屬性動畫會在下一篇詳細說明。
View 繪製時會呼叫 onLayout() 來設定顯示位置,因此我們可以透過修改 left、top、right、bottom 來控制座標。先在 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(getLeft() + offsetX, getTop() + offsetY,
getRight() + offsetX, getBottom() + offsetY);
break;
每次移動都呼叫 layout() 對自己重新佈局,就能達到移動效果。自定義 View 完整程式碼:
public class CustomView extends View {
private int lastX, lastY;
public CustomView(Context context, AttributeSet attrs) { super(context, attrs); }
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;
}
}
佈局中引用這個自定義 View 即可:
<com.example.liuwangshu.moonviewslide.CustomView
android:background="@android:color/holo_red_light"
android:id="@+id/customview"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="50dp" />
這兩個方法效果與用法都與 layout() 相近,只需替換 ACTION_MOVE 中的程式碼:
case MotionEvent.ACTION_MOVE:
int offsetX = x - lastX;
int offsetY = y - lastY;
offsetLeftAndRight(offsetX); // 對 left、right 偏移
offsetTopAndBottom(offsetY); // 對 top、bottom 偏移
break;
LayoutParams 保存了一個 View 的佈局參數,改動它的 margin 即可移動 View:
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams(); layoutParams.leftMargin = getLeft() + offsetX; layoutParams.topMargin = getTop() + offsetY; setLayoutParams(layoutParams);
父容器不同要用對應的 LayoutParams(例如 RelativeLayout.LayoutParams);也可用通用的 ViewGroup.MarginLayoutParams。
可用 View 動畫移動,在 res 下建立 anim 目錄並新增 translate.xml:
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate android:duration="1000"
android:fromXDelta="0" android:toXDelta="300" />
</set>
mCustomView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.translate));
若用屬性動畫則更簡潔,讓 CustomView 在 1000 毫秒內沿 X 軸右移 300 像素:
ObjectAnimator.ofFloat(mCustomView, "translationX", 0, 300).setDuration(1000).start();
scrollTo(x, y) 移動到具體座標點,scrollBy(dx, dy) 則是移動增量,scrollBy 最終也會呼叫 scrollTo。它們移動的是 View 的「內容」;若在 ViewGroup 中使用則移動其所有子 View。要讓 CustomView 隨手指移動,需把偏移量設為負值:
((View)getParent()).scrollBy(-offsetX, -offsetY);
用 scrollTo/scrollBy 滑動是瞬間完成的,體驗不佳。Scroller 能實現帶過渡效果的滑動,但它本身不能實現滑動,必須搭配 View 的 computeScroll()。先初始化 Scroller:
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
重寫 computeScroll(),在繪製時透過 Scroller 取得當前滾動值,每滑一小段就 invalidate() 重繪,重繪又會觸發 computeScroll(),如此反覆串接即形成平滑移動:
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
}
invalidate();
}
再寫一個 smoothScrollTo(),呼叫 startScroll() 在指定時間內平移:
public void smoothScrollTo(int destX, int destY) {
int scrollX = getScrollX();
int delta = destX - scrollX;
mScroller.startScroll(scrollX, 0, delta, 0, 2000); // 2000ms 內滑向 destX
invalidate();
}
最後在 Activity 中呼叫即可,例如讓 CustomView 沿 X 軸右移 400 像素:
mCustomView.smoothScrollTo(-400, 0);
Android開發環境搭建第一步:JDK安裝與環境變量配置詳解
Android開發環境搭建第一步:JDK安裝與環境變量配置詳解 (1) 安裝JDK(Java Developer Kit)。下載JDK 1.8並安裝jdk-8u60-wi
Android 開發實踐:ListView 效能優化解析
讀過一些 vogella 的文章後,我對 Android ListView 的效能優化特別感興趣,於是動手實作,結果效能確實提升不少。 優化前後對比 優化前的 log 截
Android 自学日记(一):一个转行程序员的成长记录
Android 自学日记(一):一个转行程序员的成长记录 说起日记,记忆还停留在小学的作业里,通篇都是流水账,几点起床、去哪里玩,纯属应付。那时自知没有写作天赋,作文总要
Visual Studio 2015 Update 2 裝了 Xamarin 之後,axml 檔案失去智慧提示的解法
在 VS 2015 Update 2 環境下裝好 Xamarin,編輯 axml 版面配置檔時卻發現完全沒有 IntelliSense,這其實是缺少 XSD 結構描述檔所