Android 帧动画

  • 在 drawable 目录下新建 frames.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">

<item
android:drawable="@drawable/p1"
android:duration="50" />

<item
android:drawable="@drawable/p2"
android:duration="50" />

<item
android:drawable="@drawable/p3"
android:duration="50" />

<item
android:drawable="@drawable/p4"
android:duration="50" />

</animation-list>
  • 在页面中调用 frames.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
android:id="@+id/iv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="@drawable/frames" />

</LinearLayout>
  • 解析并开启动画
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView iv = findViewById(R.id.iv);

AnimationDrawable animationDrawable = (AnimationDrawable) iv.getDrawable();
if(!animationDrawable.isRunning()){
animationDrawable.start();
}
}
}

  • 下面是纯代码方式实现
1
2
3
4
5
6
7
8
9
AnimationDrawable animationDrawable1 = new AnimationDrawable();
int[] ids = {R.drawable.p1,R.drawable.p2,R.drawable.p3,R.drawable.p4};
for(int i = 0 ; i < 4 ; i ++){
Drawable frame = getResources().getDrawable(ids[i]);
animationDrawable1.addFrame(frame,50);
}
animationDrawable1.setOneShot(false);
iv.setBackground(animationDrawable1);
animationDrawable1.start();

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×