安卓弹出动画

17

我在我的应用程序中有一个浮动操作按钮,我想让它以某种方式弹出,在不可见的情况下开始增大到大约60dp的大小,然后重新调整为正常大小的56dp。这怎么做呢?我知道如何进行普通的渐变动画,但不知道如何实现弹出效果。

3个回答

34

我会在res/anim中创建一个动画文件,并使用顺序缩放动画,例如:

expand_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale 
        android:fromXScale="0.0" 
        android:fromYScale="0.0"
        android:toXScale="1.1" <!--set the scale value here-->
        android:toYScale="1.1"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="400"/> <!--length of first animation-->


    <scale 
        android:fromXScale="1.1" <!--From whatever scale you set in the first animation-->
        android:fromYScale="1.1"
        android:toXScale="1.0" <!--Back to normal size-->
        android:toYScale="1.0"
        android:pivotX="50%" 
        android:pivotY="50%"
        android:startOffset="400" <!--start 2nd animation when first one ends-->
        android:duration="400"/>
</set>

然后在您的活动中:

Animation expandIn = AnimationUtils.loadAnimation(this, R.anim.expand_in);
actionButton.startAnimation(expandIn);

非常感谢。我需要使用可见性来首先隐藏按钮吗? - qwertz
如果你将第一个动画比例设置为从0.0开始,那么你就不必这样做。 - Rich Luick
它的功能完美,我唯一的问题是它开始从一个角落扩展。相反地,它应该从中心扩展。我该怎么解决这个问题? - qwertz
1
非常感谢您:已接受答案。 - qwertz
3
当我将“缩小”部分改为下降到0.9而不是1.0时,我发现这个动画更加流畅。我不确定原因是什么。添加@AhmedW的建议没有帮助。 - beyondtheteal
显示剩余4条评论

14

当我将动画切换到使用Overshoot Interpolator时,发现它比当前被接受的答案要平滑得多。

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/overshoot_interpolator" >

<scale
    android:duration="700"
    android:fromXScale="0.0"
    android:fromYScale="0.0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1.0"
    android:toYScale="1.0" />

</set>
这里有一个视频展示插值器的例子:https://www.youtube.com/watch?v=OMOJxBe9KGg 这里是在Android文档中提到的位置:https://developer.android.com/guide/topics/resources/animation-resource.html#View

4

我采用了原始答案,但增加了额外的动画层,以获得更好的弹出效果。

enter code here
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
    android:duration="100"
    android:fromXScale="0.0"
    android:fromYScale="0.0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1.2"
    android:toYScale="1.2" />

<scale
    android:duration="100"
    android:fromXScale="1.2"
    android:fromYScale="1.2"
    android:pivotX="50%"
    android:pivotY="50%"
    android:startOffset="100"
    android:toXScale="0.8"
    android:toYScale="0.8" />

<scale
    android:duration="100"
    android:fromXScale="0.8"
    android:fromYScale="0.8"
    android:pivotX="50%"
    android:pivotY="50%"
    android:startOffset="100"
    android:toXScale="1.0"
    android:toYScale="1.0" />
</set>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接