当前位置: 移动技术网 > IT编程>移动开发>Android > Android自定义View实现随手势滑动控件

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

李满林,宁波客运中心时刻表,极道修真

本文控件为大家分享了android随手势滑动控件的具体代码,供大家参考,具体内容如下

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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网