当您尝试从资产目录加载 gif 时,它不是动画的,您应该为此使用 GifWebView。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#da4040" >
<WebView
android:id="@+id/webviewActionView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="200dp"
android:minWidth="200dp"
android:scrollbars="none" >
</WebView>
</RelativeLayout>
MainActivity.java
package com.test2;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView webviewActionView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InputStream stream = null;
try {
stream = getAssets().open("loading2.gif");
} catch (Exception e) {
e.printStackTrace();
}
webviewActionView = (WebView)findViewById(R.id.webviewActionView);
webviewActionView.setWebViewClient(new MyWebViewClient());
webviewActionView.getSettings().setJavaScriptEnabled(true);
GifWebView view = new GifWebView(this, stream);
webviewActionView.addView(view);
}
private class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
GifWebView.java
package com.test2;
import java.io.InputStream;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.os.SystemClock;
import android.view.View;
public class GifWebView extends View {
private Movie mMovie;
InputStream mStream;
long mMoviestart;
public GifWebView(Context context, InputStream stream) {
super(context);
mStream = stream;
mMovie = Movie.decodeStream(mStream);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
super.onDraw(canvas);
final long now = SystemClock.uptimeMillis();
if (mMoviestart == 0) {
mMoviestart = now;
}
final int relTime = (int) ((now - mMoviestart) % mMovie.duration());
mMovie.setTime(relTime);
mMovie.draw(canvas, 10, 10);
this.invalidate();
}
}
将“ loading2.gif ”文件放在您的资产目录中。
从下面的链接下载这个完整的deom
下载演示