Android

Android Drawable Animation(幀動畫)教學

1.先備妥圖片




2.在drawable下建立一個xml檔(loading.xml)

<?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/loading_1" android:duration="200"/>
    <item android:drawable="@drawable/loading_2" android:duration="200"/>
    <item android:drawable="@drawable/loading_3" android:duration="200"/>
    <item android:drawable="@drawable/loading_4" android:duration="200"/>
</animation-list>

3.自定義要顯示的畫面(loading_layout.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    <ImageView
        android:id="@+id/loading_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>

4.自定義的畫面添加到AlertDialog

val view = LayoutInflater.from(this).inflate(R.layout.loading_layout,null)
val loadingImg: ImageView = view.findViewById(R.id.loading_img)
loadingImg.setBackgroundResource(R.drawable.loading)

val animationDrawable = loadingImg.background as AnimationDrawable
animationDrawable.start()
val alert = AlertDialog.Builder(this)
    .setView(view)
    .create()

val window = alert.window
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
alert.show()

5.完成動畫

發表迴響