我看到这个问题很受欢迎,所以我贴出了我的实际解决方案。主要的优点是您不需要知道扩展的高度才能应用动画,并且一旦视图被展开,如果内容发生变化,它就会适应高度。对我来说很管用。publicstaticvoidexpand(finalViewv){
intmatchParentMeasureSpec=View.MeasureSpec.makeMeasureSpec(((View)v.getParent()).getWidth(),View.MeasureSpec.EXACTLY);
intwrapContentMeasureSpec=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
v.measure(matchParentMeasureSpec,wrapContentMeasureSpec);
finalinttargetHeight=v.getMeasuredHeight();
//Olderversionsofandroid(preAPI21)cancelanimationsforviewswithaheightof0.
v.getLayoutParams().height=1;
v.setVisibility(View.VISIBLE);
Animationa=newAnimation()
{
@Override
protectedvoidapplyTransformation(floatinterpolatedTime,Transformationt){
v.getLayoutParams().height=interpolatedTime==1
?LayoutParams.WRAP_CONTENT:(int)(targetHeight*interpolatedTime);
v.requestLayout();
}
@Override
publicbooleanwillChangeBounds(){
returntrue;
}
};
//Expansionspeedof1dp/ms
a.setDuration((int)(targetHeight/v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);}publicstaticvoidcollapse(finalViewv){
finalintinitialHeight=v.getMeasuredHeight();
Animationa=newAnimation()
{
@Override
protectedvoidapplyTransformation(floatinterpolatedTime,Transformationt){
if(interpolatedTime==1){
v.setVisibility(View.GONE);
}else{
v.getLayoutParams().height=initialHeight-(int)(initialHeight*interpolatedTime);
v.requestLayout();
}
}
@Override
publicbooleanwillChangeBounds(){
returntrue;
}
};
//Collapsespeedof1dp/ms
a.setDuration((int)(initialHeight/v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);}
正如@Jefferson在评论中所提到的,您可以通过更改动画的持续时间(以及速度)来获得更流畅的动画。目前,它已被设置为1dp/ms。
如果觉得《Android自动伸展动画 Android:展开/折叠动画》对你有帮助,请点赞、收藏,并留下你的观点哦!