一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2017-04-16 编辑:简简单单 来源:一聚教程网

1.新建自定义控件类:MyView

 

 代码如下 复制代码

publicclassMyViewextendsButton{

//记录上次滑动后的坐标值

privateintlastX;

privateintlastY;

 

publicMyView(Context context) {

  super(context);

  // TODO Auto-generated constructor stub

}

publicMyView(Context context, AttributeSet attrs){

 

  super(context, attrs);

}

 

@Override

publicbooleanonTouchEvent(MotionEvent event) {

  // 获取view相对于手机屏幕的xy值

  intx=(int) event.getRawX();

  inty=(int) event.getRawY();

  switch(event.getAction()) {

    caseMotionEvent.ACTION_DOWN:

 

      break;

    caseMotionEvent.ACTION_MOVE:

      intdeltaX=x-lastX;

      intdeltaY=y-lastY;

      inttranslationX = (int) (ViewHelper.getTranslationX(this) + deltaX);

      inttranslationY = (int) (ViewHelper.getTranslationY(this) + deltaY);

      ViewHelper.setTranslationX(this,translationX);

      ViewHelper.setTranslationY(this,translationY);

 

      break;

    caseMotionEvent.ACTION_UP:

      break;

    default:

      break;

  }

  lastX = x;

  lastY = y;

  returntrue;

}

 

上面代码就是一个自定义按钮类,重写onTouchEvent()方法来监听用户滑动,既然说到滑动肯定会存在偏移量的说法。

translationX、translationY是View左上角相对于父布局的偏移量。通过第三方nineoldandroids来实现动画滑动。

ViewHelper.getTranslationY(this)计算该View的偏移量,初始值为0,向左偏移值为负,向右偏移值为正。

2.xml布局

 

 代码如下 复制代码

 xmlns:tools="http://schemas.android.com/tools"

 android:layout_width="match_parent"

 android:layout_height="match_parent"

>

 

 

   android:id="@+id/myview"

   android:layout_width="wrap_content"

   android:layout_height="wrap_content"

   android:text="我可以滑动"/>

 

 

热门栏目