上一篇我們了解了Android的坐標系和觸控事件,今天我們就來看看Android中如何使用系統提供的API來具體實現滑動效果。實現滑動效果的六種方法之Layout方法,在這里我們要明確一件事情,無論是哪種方式,滑動效果實現的基本思想是:當觸摸View時,系統記錄下當前的坐標系;當手指移動時,系統記錄下移動后觸摸的坐標系,從而獲取到相對于前一次坐標點的偏移量,并通過偏移量來修改View的坐標,這樣不斷重復,從而實現Android的滑動效果。
下面,我們就來看一個實例,來了解一下在Android中是如何實現滑動效果的。
新建項目,然后自定義一個view,代碼如下:
package com.example.testdragview;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class DragView extends View{
private int lastX;
private int lastY;
public DragView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public DragView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DragView(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 offX = x - lastX;
int offY = y - lastY;
//調用layout方法來重新放置它的位置
layout(getLeft()+offX, getTop()+offY,
getRight()+offX , getBottom()+offY);
break;
}
return true;
}
}
核心代碼就是onTouchEvent方法了。代碼很簡單,無非就是記錄手指的上次坐標與下次坐標,然后將前后移動的增量傳遞給layout方法而已。
值得注意的是,onTouchEvent的返回值為true,表示我們要成功消化掉這個觸摸事件。
然后再修改activity_main.xml的代碼,將這個view裝到布局里,如下:
<LinearLayout xmlns:android="//schemas.android.com/apk/res/android"
xmlns:tools="//schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.testdragview.DragView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#FF0000" />
</LinearLayout>