View的滑动方式有layout()、offsetLeftAndRight()与offsetTopAndBottom()、LayoutParams、scrollTo与scrollBy、Scroller、动画(视图动画,非属性动画)。
layout()
实现View的子类,并且重写onTouchEvent(MotionEvent event),在点击该View的时候,会不断调用该方法,在此放方法中进行调用layout()进行重绘刷新,达到视图的滑动。
public boolean onTouchEvent(MotionEvent event){
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN://按下
lastX = x;//每一次移动在X方向的偏移量
lastY = y;//每一次移动在Y方向的偏移量
break;
case MotionEvent.ACTION_UP://按下之后的放开的动作
Log.d(TAG, "onTouchEvent: ");
break;
case MotionEvent.ACTION_MOVE://触碰点移动的时候
int offsetX = x-lastX;//是指每次的触碰点的偏移量
int offsetY = y-lastY;
layout(getLeft()+offsetX,getTop()+offsetY,getRight()+offsetX,getBottom()+offsetY);//重绘
break;
}
return true;
}
offsetLeftAndRight()与offsetTopAndBottom()
实现方法同layout(),只需要将layout替换为下面
offsetLeftAndRight(offsetX); offsetTopAndBottom(offsetY);
LayoutParams
不断改变布局参数
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)getLayoutParams();
layoutParams.leftMargin = getLeft()+offsetX;
layoutParams.topMargin = getTop()+offsetY;
setLayoutParams(layoutParams);
scrollTo与scrollBy
((View)getParent()).scrollBy(-offsetX,-offsetY);
Scroller
实现过渡滑动效果
视图动画
在res新建文件夹anim并新建文件translate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<translate
android:duration="1000"
android:fromXDelta="0"
android:toXDelta="300" />
</set>
在MainActivity中添加
customView.setAnimation(AnimationUtils.loadAnimation(this,R.anim.translate));
此时,此控件能够向右平移一定长度。但是如果给视图设置点击事件则不会在新的位置进行响应,而是在原来的位置响应,原因是该方式只是进行视图上的平移,而不是View的参数平移。