Android之自定义View实现随手势滑动的控件

来源:互联网 发布:淘宝客推广爆款的技巧 编辑:程序博客网 时间:2024/04/29 19:34

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);}@Overridepublic 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>
1 0
原创粉丝点击