上一篇我们了解了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="http://schemas.android.com/apk/res/android"
xmlns:tools="http://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>