ValueAnimator/Expand/Collapse 视图未提供正确的高度

ValueAnimator/Expand/Collapse view not giving correct height

我有一个搜索栏,当在工具栏中单击图标时它会展开。现在,展开时一切都很酷,一切正常,不好的是搜索栏折叠时高度不好。折叠搜索栏时工具栏的高度比原来高。这是代码:

private void expand(View view) {
    //set Visible
    view.setVisibility(View.VISIBLE);

    final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    view.measure(widthSpec, heightSpec);

    ValueAnimator mAnimator = slideAnimator(0, view.getMeasuredHeight(), view);
    mAnimator.start();
}

private ValueAnimator slideAnimator(int start, int end, final View view) {

    ValueAnimator animator = ValueAnimator.ofInt(start, end);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            //Update Height
            int value = (Integer) valueAnimator.getAnimatedValue();
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.height = value;
            view.setLayoutParams(layoutParams);
        }
    });
    return animator;
}


private void collapse(final View view) {
    int finalHeight = view.getHeight();

    ValueAnimator mAnimator = slideAnimator(finalHeight, 0, view);

    mAnimator.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animator) {
            //Height=0, but it set visibility to GONE
            view.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    });
    mAnimator.start();
}

这里一切都很好,如果要更改背景或工具栏的任何其他 属性,请检查调用方法的位置。