Andorid开发自定义View(二)滑动

对着背影说爱祢 提交于 2019-12-17 09:42:40

1 动画

可以采用View动画来移动,需要在res目录中新建anim文件夹并创建translate.xml文件

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="1000"
        android:fillAfter="true"
        android:fromXDelta="0"
        android:toXDelta="300" />
</set>

 fromXDelta 属性为动画起始时 X坐标上的位置  
 toXDelta   属性为动画结束时 X坐标上的位置  
 fromYDelta 属性为动画起始时 Y坐标上的位置  
 toYDelta   属性为动画结束时 Y坐标上的位置

 duration  属性为动画持续时间 (毫秒为单位) 

android:toXDelta="100%",表示自身的100%,也就是从View自己的位置开始。

android:toXDelta="80%p",表示父层View的80%,是以它父层View为参照的。

在java文件中调用

mCustomView = findViewById(R.id.mCustomView);
mCustomView.setAnimation(AnimationUtils.loadAnimation(context, R.anim.translate));

但是当使用动画时 并不会改变View位置参数,也就是说虽然View的位置移动了,但是点击移动后的View并不会触发点击事件,而点击View移动前的位置则会触发点击事件,所以需要使用属性动画来解决

ObjectAnimator.ofFloat(mCustomView, "translationX", 0, 300).setDuration(1000).start();

2 scrollTo和scrollBy

在调用scrollBy的时候

  ((View) getParent()).scrollBy(-offsetX,-offsetY);

 

3 Scroller

Scroller本身不能实现View 的滑动,需要和computeScroll方法配合才能实现弹性滑动的效果。

public CustomView(Context context, @Nullable AttributeSet attrs)
    {
        super(context, attrs);
        scroller = new Scroller(context);
    }

    @Override
    public void computeScroll()
    {
        super.computeScroll();
        if (scroller.computeScrollOffset())
        {
            ((View) getParent()).scrollTo(scroller.getCurrX(), scroller.getCurrY());
            invalidate();
        }
    }
public void smoothScrollTo(int destX, int destY)
    {
        int scroollX = getScrollX();
        int delta = destX -scroollX;
        scroller.startScroll(scroollX,0,delta,0,2000);
        invalidate();//无效

    }

 

之后再java中调用smoothScrollTo方法

mCustomView.smoothScrollTo(-400, 0);

 

 

 

 

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!