Android之自定義View實現隨手勢滑動的控件
1.新建自定義控件類:MyView
public class MyView extends Button{
//記錄上次滑動後的座標值
private int lastX;
private int lastY;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyView(Context context, AttributeSet attrs){
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// 獲取view相對於手機屏幕的xy值
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-lastX;
int deltaY=y-lastY;
int translationX = (int) (ViewHelper.getTranslationX(this) + deltaX);
int translationY = (int) (ViewHelper.getTranslationY(this) + deltaY);
ViewHelper.setTranslationX(this,translationX);
ViewHelper.setTranslationY(this,translationY);
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
lastX = x;
lastY = y;
return true;
}
上面代碼就是一個自定義按鈕類,重寫onTouchEvent()方法來監聽用戶滑動,既然說到滑動肯定會存在偏移量的說法。
translationX、translationY是View左上角相對於父佈局的偏移量。通過第三方nineoldandroids來實現動畫滑動。
ViewHelper.getTranslationY(this)計算該View的偏移量,初始值爲0,向左偏移值爲負,向右偏移值爲正。
2.xml佈局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.administrator.slide.MyView
android:id="@+id/myview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我可以滑動"/>
</RelativeLayout>