Android: Expand/collapse animation

后端 未结 30 2589
说谎
说谎 2020-11-22 05:01

Let\'s say I have a vertical linearLayout with :

[v1]
[v2]

By default v1 has visibily = GONE. I would like to show v1 with an expand animat

30条回答
  •  庸人自扰
    2020-11-22 05:31

    Best solution for expand/collapse view's:

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            View view = buttonView.getId() == R.id.tb_search ? fSearch : layoutSettings;
            transform(view, 200, isChecked
                ? ViewGroup.LayoutParams.WRAP_CONTENT
                : 0);
        }
    
        public static void transform(final View v, int duration, int targetHeight) {
            int prevHeight  = v.getHeight();
            v.setVisibility(View.VISIBLE);
            ValueAnimator animator;
            if (targetHeight == ViewGroup.LayoutParams.WRAP_CONTENT) {
                v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                animator = ValueAnimator.ofInt(prevHeight, v.getMeasuredHeight());
            } else {
                animator = ValueAnimator.ofInt(prevHeight, targetHeight);
            }
            animator.addUpdateListener(animation -> {
                v.getLayoutParams().height = (animation.getAnimatedFraction() == 1.0f)
                        ? targetHeight
                        : (int) animation.getAnimatedValue();
                v.requestLayout();
            });
            animator.setInterpolator(new LinearInterpolator());
            animator.setDuration(duration);
            animator.start();
        }
    

提交回复
热议问题