Search code examples
androidxmlbackgroundandroid-viewpager

How to set a fixed background in ViewPager


I have a Fragment that contains a ViewPager which allows the user to swipe through three fragments.

Here's the problem: I want the ViewPager to have a background that remains fixed when the user swipes through the fragments. I tried setting an image in my drawable as the background of the ViewPager but that didn't work.. Here's my code:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue"
    tools:context=".fragments.cash.WalletFragment">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:background="@drawable/revenue"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Solution

  • Although there are many ways to achieve this feat, this approach works for me:

    Simply create a FrameLayout with two children: Your ViewPager and the view(s) you want to use as the background of your viewpager. Here's an example:

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/blue"
        tools:context=".fragments.cash.WalletFragment">
    
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/my_smiling_face"/>
    
            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    
        </FrameLayout>
    
    </RelativeLayout>
    

    Note that you can replace the Imageview with a layout (e.g RelativeLayout) containing all the composite views you want your background to contain.

    I hope this helps.. Merry coding!