下拉scrollView

首先介绍两个方法:
public TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
public void layout(int left, int top, int right, int bottom)
以上2个方法都是改变view的位置,而Animation使用的坐标系是以自己控件的左上角为原点的自己的坐标系;而layout函数则会改变控件大小和位置,在改变位置的同时,也改变了控件的坐标系,即layout的左上角始终是这个布局的(0,0)原点;
下拉回弹效果

/**
     * 完成布局解析
     */
    @Override
    protected void onFinishInflate() {
        //scrollview只能有一个布局,因此0就是根布局
        mRootView = getChildAt(0);
        super.onFinishInflate();
    }
    private int mpreY = 0;//保存手指移动的最新位置
    private Rect mNormalRect;//原始跟视图对应的位置

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float curY = event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(mRootView != null){
                    //获取原始根视图对应的位置
                    mNormalRect = new Rect(mRootView.getLeft(),mRootView.getTop(),
                            mRootView.getRight(), mRootView.getBottom());
                }
                break;
            case MotionEvent.ACTION_MOVE:
                //event.getY() - mpreY就可以得到当前手指的移动距离
                //乘以0.25的原因.如果我们不想让布局的移动距离跟手指的移动距离等同。
                // 让布局的移动距离比手指移动距离小,会给用户一种有阻力的感觉。
                int delta = (int) ((curY - mpreY)*0.25);
                if(delta > 0)
                    mRootView.layout(mRootView.getLeft(),
                            mRootView.getTop()+delta,
                            mRootView.getRight(),
                            mRootView.getBottom()+delta);
                break;
            case MotionEvent.ACTION_UP:
                int curTop = mRootView.getTop();
                mRootView.layout( mNormalRect.left, mNormalRect.top, mNormalRect.right, mNormalRect.bottom);
                TranslateAnimation animation = new TranslateAnimation(0, 0, mRootView.getTop() - mNormalRect.top, 0);
                animation.setDuration(200);
                mRootView.startAnimation(animation);
                break;
        }
        mpreY = (int) curY;
        return super.onTouchEvent(event);
    }

稍微解释下上面的代码

  1. 首先继承scrollView,在onFinishInflate方法中,即完成布局解析时得到根布局view。
  2. 当手指按下时获取原始根视图的位置Rect()
  3. 当手指移动时,保存手指移动的最新位置
  4. 当手指抬起时,将视图布局重新移动到原来位置,然后用动画效果平移到原来位置。
    差不多就是这样了,用这个自定义控件就可以实现下拉回弹效果了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值