1

I finally figured out a (mostly copy-pasting code) simple way to play animated GIF in the app so that I can use it as a preloader. I am using a DialogFragment with a WebView inside. All is well except that the image is shown in the left corner of the screen, centered vertically. Here is my code inside DialogFragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_please_wait, container, false);
        WebView gifPlayer = (WebView) view.findViewById(R.id.gifPlayer);
        gifPlayer.loadUrl("file:///android_asset/img/preloader_7.gif");
        gifPlayer.setBackgroundColor(0x00000000);

        // http://stackoverflow.com/questions/9698410/position-of-dialogfragment-in-android
        getDialog().getWindow().setGravity(Gravity.CENTER);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        return view;
    }  

and my XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:background="@android:color/transparent"
    android:orientation="vertical" >

    <WebView
        android:background="@android:color/transparent"
        android:id="@+id/gifPlayer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>  

How do I position it in the center of the screen?

An SO User
  • 24,612
  • 35
  • 133
  • 221

2 Answers2

0

Just add in your xml file in the webview tag this: android:layout_gravity="center"

0

Youre RelativeLayout has to have a width of "fill_parent" for this to work.

Your Editor should give you a warning about this, at least Android Studio does.

Try this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@android:color/transparent"
android:orientation="vertical" >

<WebView
    android:background="@android:color/transparent"
    android:id="@+id/gifPlayer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />

Senchay
  • 121
  • 1
  • 8