这篇目的一是记录下,二是将这个效果发布出来,网上虽然很多但是太模糊了。
8多说先看效果
record_20190820161240530.gif上代码
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import androidx.appcompat.widget.AppCompatImageView;
/**
* Created by TU on 2019/3/14.
* 具有折叠展开伸缩动画
*/
public class ExpandLayout extends RelativeLayout {
private View layoutView;
private int viewHeight;
private boolean isExpand;
private long animationDuration;
private boolean lock;
public ExpandLayout(Context context) {
this(context, null);
}
public ExpandLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ExpandLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView() {
layoutView = this;
isExpand = true;
animationDuration = 300;
setViewDimensions();
}
/**
* @param isExpand 初始状态是否折叠
*/
public void initExpand(boolean isExpand) {
this.isExpand = isExpand;
setViewDimensions();
}
/**
* 设置动画时间
*
* @param animationDuration 动画时间
*/
public void setAnimationDuration(long animationDuration) {
this.animationDuration = animationDuration;
}
/**
* 获取subView的总高度
* View.post()的runnable对象中的方法会在View的measure、layout等事件后触发
*/
private void setViewDimensions() {
layoutView.post(new Runnable() {
@Override
public void run() {
if (viewHeight <= 0) {
viewHeight = layoutView.getMeasuredHeight();
}
setViewHeight(layoutView, isExpand ? viewHeight : 0);
}
});
}
public static void setViewHeight(View view, int height) {
final ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = height;
view.requestLayout();
}
/**
* 切换动画实现
*/
private void animateToggle(long animationDuration) {
ValueAnimator heightAnimation = isExpand ?
ValueAnimator.ofFloat(0f, viewHeight) : ValueAnimator.ofFloat(viewHeight, 0f);
heightAnimation.setDuration(animationDuration / 2);
heightAnimation.setStartDelay(animationDuration / 2);
heightAnimation.addUpdateListener(animation -> {
int value = (int) (float) animation.getAnimatedValue();
setViewHeight(layoutView, value);
if (value == viewHeight || value == 0) {
lock = false;
}
});
heightAnimation.start();
lock = true;
}
public boolean isExpand() {
return isExpand;
}
/**
* 折叠view
*/
public void collapse() {
isExpand = false;
animateToggle(animationDuration);
}
/**
* 展开view
*/
public void expand() {
isExpand = true;
animateToggle(animationDuration);
}
/**
* @param imageView 展开时旋转角标
*/
public void toggleExpand(AppCompatImageView imageView) {
if (lock) {
return;
}
if (isExpand) {
collapse();
imageView.animate().rotation(0);
} else {
expand();
imageView.animate().rotation(90);
}
}
}
调用
@BindView(R.id.expand)
ExpandLayout expand;
//oncreate()初始化
expand.initExpand(false);
//传入被执行动画的view
expandPopular.toggleExpand(imgae);
soeasy,拿别人的轮子来改造了下,具体根据自己需求更改view代码。
网友评论