爲View設置左右切換動畫

本文同步自http://javaexception.com/archives/64html

問題:

近期的需求中,碰到了一個view切換動畫的需求。要實現的是點擊按鈕,從左到右滑動view,左邊的view消失,右邊的view出現。有點像文字跑馬燈的效果,不過此次滾動的是view,具體看截圖效果。java

 

實現思路:

晚上在家寫了一個比較low的實現方案,參考的思路是Banner輪播的思路,用viewPager來進行view的切換。大體效果也還行,只不過以爲代碼量太多,使用比較麻煩。我就是想給兩個view加上能夠切換動畫的效果,就要寫那麼多的代碼,感受不划算。只好放棄此方案。android

隨後想到了swipeView,發現這是一個挺好的點,能夠從這裏入手。通過對swipeMenuLayout代碼的閱讀分析以及測試實踐。得出瞭如下的解決方案。ide

自定義SlideLayout.java函數

public class SlideLayout extends ViewGroup {
    private static final String TAG = "SlideLayout";
    private int mHeight;
    private View mContentView;
    private View mRightView;
    private boolean isAnimation = false;

    public SlideLayout(Context context) {
        this(context, null);
    }

    public SlideLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //Log.d(TAG, "onMeasure() called with: " + "widthMeasureSpec = [" + widthMeasureSpec + "], heightMeasureSpec = [" + heightMeasureSpec + "]");
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mHeight = 0;
        int contentWidth = 0;
        int childCount = getChildCount();

        final boolean measureMatchParentChildren = MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        boolean isNeedMeasureChildHeight = false;

        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getVisibility() != GONE) {
                measureChild(childView, widthMeasureSpec, heightMeasureSpec);
                final MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
                mHeight = Math.max(mHeight, childView.getMeasuredHeight()/* + lp.topMargin + lp.bottomMargin*/);
                if (measureMatchParentChildren && lp.height == LayoutParams.MATCH_PARENT) {
                    isNeedMeasureChildHeight = true;
                }
                if (i == 0) {
                    mContentView = childView;
                    contentWidth = childView.getMeasuredWidth();
                } else {
                    mRightView = childView;
                }
            }
        }
        setMeasuredDimension(getPaddingLeft() + getPaddingRight() + contentWidth,
                mHeight + getPaddingTop() + getPaddingBottom());//寬度取第一個Item(Content)的寬度
        if (isNeedMeasureChildHeight) {//若是子View的height有MatchParent屬性的,設置子View高度
            forceUniformHeight(childCount, widthMeasureSpec);
        }
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    /**
     * 給MatchParent的子View設置高度
     *
     * @param count
     * @param widthMeasureSpec
     * @see android.widget.LinearLayout# 同名方法
     */
    private void forceUniformHeight(int count, int widthMeasureSpec) {
        // Pretend that the linear layout has an exact size. This is the measured height of
        // ourselves. The measured height should be the max height of the children, changed
        // to accommodate the heightMeasureSpec from the parent
        int uniformMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
                MeasureSpec.EXACTLY);//以父佈局高度構建一個Exactly的測量參數
        for (int i = 0; i < count; ++i) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    // Temporarily force children to reuse their old measured width
                    int oldWidth = lp.width;//measureChildWithMargins 這個函數會用到寬,因此要保存一下
                    lp.width = child.getMeasuredWidth();
                    // Remeasure with new dimensions
                    measureChildWithMargins(child, widthMeasureSpec, 0, uniformMeasureSpec, 0);
                    lp.width = oldWidth;
                }
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //Log.e(TAG, "onLayout() called with: " + "changed = [" + changed + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
        int childCount = getChildCount();
        int left = 0 + getPaddingLeft();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getVisibility() != GONE) {
                if (i == 0) {//第一個子View是內容 寬度設置爲全屏
                    childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
                    left = left + childView.getMeasuredWidth();
                } else {
                    childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
                    left = left + childView.getMeasuredWidth();
                }
            }
        }
        //Log.d(TAG, "onLayout() called with: " + "maxScrollGap = [" + maxScrollGap + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
    }

    public void slideLeft(long duration) {
        if (isAnimation) {
            return;
        }
        AnimatorSet animatorSet = new AnimatorSet();
        final ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(mContentView, "translationX", 0, -mContentView.getMeasuredWidth());
        final ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(mRightView, "translationX", 0, -mContentView.getMeasuredWidth());
        animatorSet.playTogether(objectAnimator1, objectAnimator2);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                isAnimation = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isAnimation = false;
            }
        });
        animatorSet.setDuration(duration);
        animatorSet.start();
    }

    public void slideRight(long duration) {
        if (isAnimation) {
            return;
        }
        AnimatorSet animatorSet = new AnimatorSet();
        final ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(mContentView, "translationX", -mContentView.getMeasuredWidth(), 0);
        final ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(mRightView, "translationX", -mContentView.getMeasuredWidth(), 0);
        animatorSet.playTogether(objectAnimator1, objectAnimator2);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                isAnimation = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isAnimation = false;
            }
        });
        animatorSet.setDuration(duration);
        animatorSet.start();
    }
}

接着看看如何使用,調用方式。佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="向左滑動" />

        <Button
            android:id="@+id/btn_start2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="向右滑動" />
    </LinearLayout>


    <me.star.animator.SlideLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:padding="4dp"
            android:text="展現1"
            android:textSize="20sp"
            android:visibility="visible" />

        <TextView
            android:id="@+id/btn_show2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:padding="4dp"
            android:text="展現2"
            android:textSize="20sp" />

    </me.star.animator.SlideLayout>


</LinearLayout>
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnShow = findViewById(R.id.btn_show);
        btnShow2 = findViewById(R.id.btn_show2);
        btnStart = findViewById(R.id.btn_start);
        btnStart2 = findViewById(R.id.btn_start2);
        container = findViewById(R.id.container);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                container.slideLeft(3000);
            }
        });

        btnStart2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                container.slideRight(3000);
            }
        });
    }

其餘相關:

看到泡網上有一個爲View和Activity設置左右切換動畫的文章http://www.jcodecraeer.com/a/basictutorial/2016/1014/6672.html測試

代碼下載:

連接:https://pan.baidu.com/s/1Tg7-eJYSOZqEGU-fQY4how 密碼:c8q8動畫

相關文章
相關標籤/搜索