控件隐藏显示动画

点击按钮显示隐藏的布局,这样的需求很常见,例如树形结构点击节点显示更多节点。添加动画过渡会让界面显得更加流畅。

1. 实现原理

在布局显示之前计算布局的宽高,然后通过属性动画一点点增加LayoutParams的宽高值;在隐藏的的时候则减小宽高值。

2.调用代码
heightExtended(View parentView, View childView)//显示View

parentView 是隐藏View直接父View 只有获取了父View的 MeasureSpace才能计算子View的宽高

heightshinked(View childview)//隐藏View

此时view已经显示 系统已经计算好宽高,所以不要在传入父View
第二行加了动画,第三行没有动画。对比很明显

在这里插入图片描述

3. 源码

源码引入了lambda 表达式,需要在在build.gradle中做一下配置,不想配置就使用匿名类代替

 defaultConfig {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
/**
     * 在特效中展开
     *
     * @param parentView 为了获取父控件的MeasureSpace
     * @param childView
     */
    public void heightExtended(View parentView, View childView) {
        childView.measure(parentView.getMeasuredWidth(), parentView.getMeasuredHeight());
        int viewHeigh = View.MeasureSpec.getSize(childView.getMeasuredHeight());
        if (childView.getLayoutParams() == null) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, 0);
            childView.setLayoutParams(lp);
        } else {
            childView.getLayoutParams().height = 0;
        }
        childView.setVisibility(View.VISIBLE);
        ValueAnimator va = ValueAnimator.ofInt(0, viewHeigh);
        va.start();
        va.addUpdateListener(animation -> {
            animation.getAnimatedValue();
            int currentValue = (Integer) animation.getAnimatedValue();
//            System.out.println(currentValue);
            childView.getLayoutParams().height = currentValue;
            childView.requestLayout();
        });
    }


/**
     * 在特效中收缩
     *
     * @param childview
     */
    public void heightshinked(View childview) {
        ValueAnimator va = ValueAnimator.ofInt(View.MeasureSpec.getSize(childview.getMeasuredHeight()), 0);
        va.start();
        va.addUpdateListener(animation -> {
            animation.getAnimatedValue();
            int currentValue = (Integer) animation.getAnimatedValue();
//            System.out.println(currentValue);
            childview.getLayoutParams().height = currentValue;
            childview.requestLayout();
            if (currentValue == 0) {
                childview.setVisibility(View.GONE);
            }
        });
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值