注意:邊看視頻邊敲代碼,一樣的步驟又出現了問題,在新建xml文件時要建在drawable目錄下,不要建在anim下,不然會出錯
第一步:先添加圖片在drawable的mdpi下
第二步:創建fairy.xml在drawable目錄下
<?xml version="1.0" encoding="utf-8"?>
<!--使用逐幀動畫,要將set修改爲animation-list,每張圖片顯示60毫秒-->
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/peo1" android:duration="60"/>
<item android:drawable="@drawable/peo2" android:duration="60"/>
<item android:drawable="@drawable/peo3" android:duration="60"/>
<item android:drawable="@drawable/peo4" android:duration="60"/>
<item android:drawable="@drawable/peo5" android:duration="60"/>
<item android:drawable="@drawable/peo6" android:duration="60"/>
</animation-list>
第三步:在佈局文件中使用動畫資源文件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:background="@drawable/fairy"//添加動畫資源文件
android:id="@+id/linearlayout"
tools:context=".MainActivity">
</LinearLayout>
第四步:控制動畫的開始與停止MainActivity.java
package com.example.animafairy;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private boolean flag=true;//記錄播放狀態
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout=findViewById(R.id.linearlayout);
final AnimationDrawable anim= (AnimationDrawable) linearLayout.getBackground();//獲取動畫Drawable資源
//爲佈局管理器添加單擊事件,實現單擊屏幕開始動畫和結束動畫
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(flag)//如果動畫爲真,就播放動畫
{
anim.start();//播放動畫
flag=false;
}else
{
anim.stop();//停止動畫
flag=true;
}
}
});
}
}
運行結果
設置橫屏顯示
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.animafairy">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="landscape">//橫屏代碼
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>