首页 > 解决方案 > Android 动画在 ClickListener() 上不起作用

问题描述

好的,所以当我单击我的 ConstraintLayout 时,我的 RecyclerView 应该变为可见,当我再次单击同一个 ConstraintLayout 时,我的 RecyclerView 变为 GONE。那部分工作正常......但它是即时的,否则我的动画不起作用。我希望我的动画持续一秒钟左右,但它是即时的并且看起来很难看。

我的扩展代码:

 public static void expand(final View v) {
    int matchParentMeasureSpec = View.MeasureSpec.makeMeasureSpec(((View) v.getParent()).getWidth(), View.MeasureSpec.EXACTLY);
    int wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    v.measure(matchParentMeasureSpec, wrapContentMeasureSpec);
    final int targetHeight = v.getMeasuredHeight();

    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? ViewGroup.LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // Expansion speed of 1dp/ms
    a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density) * 1000);
    v.startAnimation(a);
}

和崩溃:

  public static void collapse(final View v) {
    final int initialHeight = v.getMeasuredHeight();
    v.setVisibility(View.GONE);
    Animation a = new Animation()

    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if(interpolatedTime == 1){
                v.setVisibility(View.GONE);
            }else{
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // Collapse speed of 1dp/ms
    a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density) *1000);
    v.startAnimation(a);
}

标签: javaandroidandroid-recyclerview

解决方案


推荐阅读