问题描述
我有一个 LinearLayout
,我想用 Animation
显示或隐藏它,每当我改变它的可见性时,它就会向上或向下推动布局.
I have a LinearLayout
that I want to show or hide with an Animation
that pushes the layout upwards or downwards whenever I change its visibility.
我看过一些样本,但没有一个适合我的需要.
I've seen a few samples out there but none of them suit my needs.
我为动画创建了两个 xml 文件,但是当我更改 LinearLayout
的可见性时,我不知道如何启动它们.
I have created two xml files for the animations but I do not know how to start them when I change the visibility of a LinearLayout
.
推荐答案
使用 Android 3.0 (Honeycomb) 中引入的新动画 API,创建此类动画非常简单.
With the new animation API that was introduced in Android 3.0 (Honeycomb) it is very simple to create such animations.
将 View
向下滑动一段距离:
Sliding a View
down by a distance:
view.animate().translationY(distance);
您可以稍后将 View
滑动回其原始位置,如下所示:
You can later slide the View
back to its original position like this:
view.animate().translationY(0);
您还可以轻松组合多个动画.以下动画将一个 View
向下滑动高度并同时淡入:
You can also easily combine multiple animations. The following animation will slide a View
down by its height and fade it in at the same time:
// Prepare the View for the animation
view.setVisibility(View.VISIBLE);
view.setAlpha(0.0f);
// Start the animation
view.animate()
.translationY(view.getHeight())
.alpha(1.0f)
.setListener(null);
然后您可以淡出 View
并将其滑回其原始位置.我们还设置了一个 AnimatorListener
,这样我们就可以在动画完成后将 View
的可见性设置回 GONE
:
You can then fade the View
back out and slide it back to its original position. We also set an AnimatorListener
so we can set the visibility of the View
back to GONE
once the animation is finished:
view.animate()
.translationY(0)
.alpha(0.0f)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
这篇关于显示和隐藏带有向上/向下滑动动画的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!