为View设置左右切换动画

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

问题:

近期的需求中,碰到了一个view切换动画的需求。要实现的是点击按钮,从左到右滑动view,左边的view消失,右边的view出现。有点像文字跑马灯的效果,不过这次滚动的是view,具体看截图效果。

为View设置左右切换动画_第1张图片

 

实现思路:

晚上在家写了一个比较low的实现方案,参考的思路是Banner轮播的思路,用viewPager来进行view的切换。大致效果也还行,只不过觉得代码量太多,使用比较麻烦。我就是想给两个view加上可以切换动画的效果,就要写那么多的代码,感觉不划算。只好放弃此方案。

随后想到了swipeView,发现这是一个挺好的点,可以从这里入手。经过对swipeMenuLayout代码的阅读分析以及测试实践。得出了以下的解决方案。

自定义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();
    }
}

接着看看如何使用,调用方式。





    

        
@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

你可能感兴趣的:(android)