安卓(Android) 怎么验证视图可见性状态并执行适当的动画(Animation)以展开或折叠

2019年10月15日20:28:32安卓(Android) 怎么验证视图可见性状态并执行适当的动画(Animation)以展开或折叠已关闭评论 256 1919字阅读6分23秒

1.简介

安卓(Android) 怎么验证视图可见性状态并执行适当的动画(Animation)以展开或折叠?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class Main{

    public static final void horizontalExpandTranformation(View viewValue) {

        if (viewValue.getVisibility() == View.VISIBLE) {
            AnimationUtils.horizontalCollapse(viewValue);
        } else {
            AnimationUtils.horizontalExpand(viewValue);
        }
    }
    public static void horizontalCollapse(final View viewValue) {
        if (viewValue.getVisibility() == View.GONE) {
            return;
        }
        final int initialWidth = viewValue.getMeasuredWidth();
        Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime,
                    Transformation transformation) {
                if (interpolatedTime == 1) {
                    viewValue.setVisibility(View.GONE);
                } else {
                    viewValue.getLayoutParams().width = initialWidth
                            - (int) (initialWidth * interpolatedTime);
                    viewValue.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        animation.setDuration((int) (initialWidth / viewValue.getContext()
                .getResources().getDisplayMetrics().density));
        viewValue.startAnimation(animation);
    }
    public static void horizontalExpand(final View viewValue) {
        if (viewValue.getVisibility() == View.VISIBLE) {
            return;
        }
        viewValue.measure(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        final int targetWidth = viewValue.getMeasuredWidth();
        viewValue.getLayoutParams().width = 0;
        viewValue.setVisibility(View.VISIBLE);
        Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime,
                    Transformation transformation) {
                viewValue.getLayoutParams().width = interpolatedTime == 1 ? ViewGroup.LayoutParams.WRAP_CONTENT
                        : (int) (targetWidth * interpolatedTime);
                viewValue.requestLayout();
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        animation.setDuration((int) (targetWidth / viewValue.getContext()
                .getResources().getDisplayMetrics().density));
        viewValue.startAnimation(animation);
    }
}

 
继续阅读