80行代码搞定菜单展开动画

其实实现动画效果是非常简单的,下面就使用ObjectAnimator来实现一个点击按钮向下展开菜单项的动画。


制作布局文件

首先我们要把我们的图片素材全部放到到一个帧布局中,将菜单键放在最上面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/b"
android:paddingLeft="5dp"
android:paddingTop="5dp"
/>

<ImageView
android:id="@+id/imageView_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/c"
android:paddingLeft="5dp"
android:paddingTop="5dp"
/>

<ImageView
android:id="@+id/imageView_d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/d"
android:paddingLeft="5dp"
android:paddingTop="5dp"
/>

<ImageView
android:id="@+id/imageView_e"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/e"
android:paddingLeft="5dp"
android:paddingTop="5dp"
/>

<ImageView
android:id="@+id/imageView_f"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/f"
android:paddingLeft="5dp"
android:paddingTop="5dp"
/>

<ImageView
android:id="@+id/imageView_g"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/g"
android:paddingLeft="5dp"
android:paddingTop="5dp"
/>
<ImageView
android:id="@+id/imageView_h"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/h"
android:paddingLeft="5dp"
android:paddingTop="5dp"
/>
<ImageView
android:id="@+id/imageView_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/a"
android:paddingLeft="2dp"
android:paddingTop="2dp"
/>
</FrameLayout>

那么接下来要做的就是把这几个菜单项目b~h依次展开。


制作动画

接下来就要分别用一个int数组来保存我们的图片id,和一个list保存我们的imageview,在onCreate方法中用for循环将id与view对象依次关联起来。给触发按钮注册监听事件。然后调用startAnim 方法。

1
2
3
4
5
6
7
8
9
10
11
12
private void startAnim()
{
for (int i = 1; i < resId.length ; i++)
{
ObjectAnimator animator=ObjectAnimator.ofFloat(imageViewList.get(i),"translationY",0F,i*150);
animator.setDuration(500);
animator.setStartDelay(i*300);
animator.setInterpolator(new BounceInterpolator());
animator.start();
}
flag=false;
}

这里的flag时标志你展开还是关闭,如果为false,调用closeAnim 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
private void closeAnim()
{
for (int i = resId.length-1; i >0 ; i--)
{
ObjectAnimator animator=ObjectAnimator.ofFloat(imageViewList.get(i),"translationY",i*150,0F);
animator.setDuration(500);
animator.setStartDelay(i*300);
animator.setInterpolator(new BounceInterpolator());


animator.start();
}
}

效果如下:
这里写图片描述
这里写图片描述