最近有呈現動態圖gif在 android app 上的需求,所以特別紀錄一下,我使用的 OS 為 windows 10,android 版本如下:

1.jpg

 

首先我們先建立各別建立 ImageView 與 Button,如下,按鈕的目的是按下後可以將靜態圖動態替換至動態圖:

<?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"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/thunder"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:text="換動態圖"
        app:layout_constraintBottom_toBottomOf="@id/thunder"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.074"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

之後需要先建立一個 assets 資料夾在 android 專案中,這是用來放置 gif 圖檔的:

1.JPG

 

然後將gif圖檔放在assets資料夾內,靜態的png/jpg檔案放在 res/drawable 中。

 

gif 動態圖的呈現需要用到下述的 dependency,要放在 gradle 檔案中。

implementation "pl.droidsonroids.gif:android-gif-drawable:1.2.2"

2.JPG

 

最後,給程式碼,裡面就是新增了一個按鈕事件,然後直接替換掉 ImageView的圖檔來源:

 

 

 

打完收工

Reference:

https://blog.csdn.net/xiaomai949804781/article/details/52872409

 

 

 

 

 

arrow
arrow

    葛瑞斯肯 發表在 痞客邦 留言(0) 人氣()