问题
Is it possible to animate using ValueAnimator
to wrap_content
? this only seems to work with constant values.
public static void valueAnimate(final View obj, int from, int to, Interpolator interpolator, long duration, long delay){
ValueAnimator anim = ValueAnimator.ofInt(from, to);
anim.setInterpolator(interpolator == null ? DEFAULT_INTERPOLATOR : interpolator);
anim.setDuration(duration);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
obj.getLayoutParams().height = value.intValue();
obj.requestLayout();
}
});
anim.setStartDelay(delay);
anim.start();
}
How could I pass a the to
parameter as wrap_content
?
Animator.valueAnimate(mapUtilsContainer, CURR_MAPUTILC_H, 800, OVERSHOOT, 300, 0);
回答1:
You can do something like this. Pass a view that is set initially to gone.
public static void expand(final View view) {
view.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final int targetHeight = view.getMeasuredHeight();
// Set initial height to 0 and show the view
view.getLayoutParams().height = 0;
view.setVisibility(View.VISIBLE);
ValueAnimator anim = ValueAnimator.ofInt(view.getMeasuredHeight(), targetHeight);
anim.setInterpolator(new AccelerateInterpolator());
anim.setDuration(1000);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = (int) (targetHeight * animation.getAnimatedFraction());
view.setLayoutParams(layoutParams);
}
});
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// At the end of animation, set the height to wrap content
// This fix is for long views that are not shown on screen
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
}
});
anim.start();
}
回答2:
An easy solution is to use android:animateLayoutChanges attribute in your layout which includes your component. This is for Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN (Android 4.3). For example, I have one EditText which needs to change from a certain height to wrap_content.
Add the android:animateLayoutChanges attribute to my ScrollView.
< ScrollView ... android:animateLayoutChanges="true">
Add this in your onCreateView()
scrollView.layoutTransition.enableTransitionType(LayoutTransition.CHANGING)
Then you will see a fairly smooth change of the EditText height.
Code to change the height of EditText to wrap_content
fun wrapText() { val layoutParams = this.layoutParams layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT this.layoutParams = layoutParams isExpanded = false }
来源:https://stackoverflow.com/questions/55251650/how-to-animate-to-wrap-content