1. 程式人生 > >最簡單的RecyclerView下拉重新整理動畫

最簡單的RecyclerView下拉重新整理動畫

首先我們的RecyclerView的根佈局是LinearLayout,所以這裡用的是LinearLayout.LayoutParams,如果是其他佈局,就用相應的LayoutParams。
首先是設定的程式碼:

        recyclerView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

對RecyclerView的監聽事件:oldY 是全域性的

        final ValueAnimator valueAnimator = ValueAnimator.ofInt(100, 0);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getActionMasked()) {
                    case
MotionEvent.ACTION_DOWN: oldY = (int) motionEvent.getY(); break; case MotionEvent.ACTION_MOVE: int newY = (int) motionEvent.getY(); if (newY - oldY > 3) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) recyclerView.getLayoutParams(); lp.topMargin += newY - oldY; recyclerView.setLayoutParams(lp); recyclerView.requestLayout(); oldY = newY; } break
; case MotionEvent.ACTION_UP: final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) recyclerView.getLayoutParams(); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { private IntEvaluator evaluator = new IntEvaluator(); @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { lp.topMargin = evaluator.evaluate( valueAnimator.getAnimatedFraction(), lp.topMargin, 0); recyclerView.setLayoutParams(lp); recyclerView.requestLayout(); } }); valueAnimator.start(); break; } return false; } });

本文完。