View——滑动

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的参数平移。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值