Android自定义View实现随手势滑动控件
本文控件为大家分享了Android随手势滑动控件的具体代码,供大家参考,具体内容如下
1.新建自定义控件类:MyView
publicclassMyViewextendsButton{
//记录上次滑动后的坐标值
privateintlastX;
privateintlastY;
publicMyView(Contextcontext){
super(context);
//TODOAuto-generatedconstructorstub
}
publicMyView(Contextcontext,AttributeSetattrs){
super(context,attrs);
}
@Override
publicbooleanonTouchEvent(MotionEventevent){
//获取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布局
<?xmlversion="1.0"encoding="utf-8"?> <RelativeLayoutxmlns: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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。