点击按钮显示隐藏的布局,这样的需求很常见,例如树形结构点击节点显示更多节点。添加动画过渡会让界面显得更加流畅。
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);
}
});
}