xml中配置
一、生成配置文件
res/drawable中生成loading.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 执行一次 android:oneshot="true" -->
<!--<animation-list android:oneshot="true" xmlns:android="http://schemas.android.com/apk/res/android">-->
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 显示毫秒:android:duration="100" -->
<item android:drawable="@drawable/frame_1" android:duration="100" />
<item android:drawable="@drawable/frame_2" android:duration="100" />
<item android:drawable="@drawable/frame_3" android:duration="100" />
</animation-list>
二、在activity_main.xml中加入View
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<View
android:id="@+id/mainView"
android:background="@drawable/loading"
android:layout_centerInParent="true"
android:layout_width="300dp"
android:layout_height="300dp"/>
<LinearLayout
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/startButtom"
android:text="Start"
android:onClick="onClick"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="@+id/stopButtom"
android:text="Stop"
android:onClick="onClick"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
</RelativeLayout>
三、代码中使用
package com.example.testframeanimation;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private AnimationDrawable animationBrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.mainView);
animationBrawable = (AnimationDrawable) view.getBackground();
// 执行一次
//animationBrawable.setOneShot(true);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.startButtom:
animationBrawable.start();
break;
case R.id.stopButtom:
animationBrawable.stop();
break;
}
}
}