Pages

Wednesday, February 12, 2014

Example to show Animated GIF image in Android

Android  doesnot support GIF image simply you should use WebView  or other thing to run gif image.
I use WebView to implement the GIF image .


First create a GIFView by extending webview.

public class GIFView extends WebView {

public static final String HTML_FORMAT = "<html><body style=\"text-align: center;  vertical-align:                       right;background-color: transparent;\"><img src = \"%s\" /></body></html>";

public GIFView(Context context, String fileUrl) throws IOException {
  super(context);


final String html = String.format(HTML_FORMAT, fileUrl);

setBackgroundColor(Color.TRANSPARENT);
loadDataWithBaseURL("", html, "text/html", "UTF-8", "");

}

}


Create your activity class here.

public class MainActivity extends Activity {

private WebView webView;
// private ProgressBar pd;
private LinearLayout llProgress;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


      llProgress = (LinearLayout) findViewById(R.id.ll_progress);
try {

//                give your gif image name here(example.gif).
GIFView gif = new GIFView(this,
"file:///android_asset/example.gif");
llProgress.addView(gif);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


here is your   activity_main   file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/ll_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal" >
    </LinearLayout>

</RelativeLayout>


3 comments:

  1. but where to store this gif file in project?

    ReplyDelete
  2. Just put the file inside the assets folder

    ReplyDelete
  3. My Gif image size resolution is huge. I'm getting the gif image like a scrolable inside webview. Any idea how to fit it exactly in WebView.

    ReplyDelete