method one:
1. gif image:
Copy the required .gif images to the drawable folder, as shown in the figure below.
2. Layout file:
Add the ImageView code snippet in the layout file as shown below.
<ImageView
android:id="@+id/img_gif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginTop="15dp"
android:scaleType="fitXY" />
3. Logic code:
Add a logic code segment in MainActivity as shown below.
ImageView img_gif = findViewById (R.id.img_gif);
//如果系统版本为Android9.0以上,则利用新增的AnimatedImageDrawable显示GIF动画
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
try {
//利用Android9.0新增的ImageDecoder读取gif动画
ImageDecoder.Source source = ImageDecoder.createSource (getResources (), R.drawable.test1);
//从数据源中解码得到gif图形数据
Drawable drawable = ImageDecoder.decodeDrawable (source);
//设置图像视图的图形为gif图片
img_gif.setImageDrawable (drawable);
//如果是动画图形,则开始播放动画
if (drawable instanceof Animatable) {
Animatable animatable = (Animatable) img_gif.getDrawable ();
animatable.start ();
}
} catch (Exception e) {
e.printStackTrace ();
}
}
Method Two:
1. Import the jre package:
Copy the downloaded glide-3-6-0.jar to the app->libs folder in the Project view, and right-click to select Add As library to import the package, as shown in the figure below.
Download link of glide-3-6-0.jar: https://www.oschina.net/news/62060/glide-3-6-0
2. gif image:
Same as Step 1 of Method 1.
3. Layout file:
Same as Step 2 of Method 1.
4. Logic code:
Add a logic code segment in MainActivity as shown below.
ImageView img_gif= (ImageView) findViewById (R.id.img_gif);
Glide.with (this).load (R.drawable.test1).into (img_gif);
Summary: In comparison, the second method is better, only two lines of code can realize this function, but remember to import the jre package.