在drawable目录下新建drawable resource file 文件chess.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/black_chess" android:duration="1000"/>
<item android:drawable="@drawable/white_chess" android:duration="1000"/>
</animation-list>
drawable 绑定图片资源;duration 设置时长,单位是毫秒(ms)
接下来更改activity_main.xml如下:
<?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"
android:orientation="vertical"
android:id="@+id/layout"
android:background="@drawable/chess"
tools:context=".MainActivity">
</LinearLayout>
设置布局id,背景设置为刚才新建的chess。id在之后加入点击时间时用到。
最后时MaingActivity.java文件。
public class MainActivity extends AppCompatActivity {
private boolean button = true; //动画状态
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = findViewById(R.id.layout); //绑定布局管理器id
final AnimationDrawable anim = (AnimationDrawable) ll.getBackground();//获取动画Drawable资源
//添加点击事件
ll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(button)
{
anim.start();
button = false;
}else {
anim.stop();
button = true;
}
}
});
}
}
最后结果: