使用nineoldandroids开源动画库.
- 通过getRawX和getRawY获得手指当前坐标A(x,y).
- 与上一次移动后的控件坐标B(mLastX,mLastY)相减得到偏移量坐标C(deltaX,deltaY),B初始化为(0,0).
- 使用ViewHelper类将控件进行动画偏移,偏移C.
- 将手指坐标即当前坐标A赋值给B.
- 循环上述操作.
例子:将button随手指移动而移动
自定义button
package com.example.test;
import com.nineoldandroids.view.ViewHelper;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
public class MyView extends Button {
int mLastX = 0; // 上次移动后最终的横坐标
int mLastY = 0; // 上次移动后最重的纵坐标
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// 当前手指坐标
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
int deltaX = x - mLastX; // x方向移动量
int deltaY = y - mLastY; // y方向移动量
int translationX = (int) (ViewHelper.getTranslationX(this) + deltaX); // x方向平移deltaX
int translationY = (int) (ViewHelper.getTranslationY(this) + deltaY); // y方向平移deltaY
ViewHelper.setTranslationX(this, translationX);
ViewHelper.setTranslationY(this, translationY);
break;
case MotionEvent.ACTION_UP:
break;
}
// 更新位置
mLastX = x;
mLastY = y;
return true;
}
}
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.test.MyView
android:id="@+id/btn"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="qqq" />
</LinearLayout>
Demo下载地址: