Add background image to individual fragments

12,437

To add background to fragment, you have to wrap it in some container

<LinearLayout
        android:id="@+id/linearlayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ccc"
        android:layout_weight="1"
        android:orientation="vertical">
    <fragment android:name="com.example.simplefragmentexample.LayOutOne"
            android:id="@+id/frag_1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>

If you wish to use same xml file, you should set images programmatically LinearLayout l = (LinearLayout) findViewById(R.id.linearlayout01); l.setBackground(Image);

or use several xmls with android:background.

Share:
12,437
Ryan Sayles
Author by

Ryan Sayles

Updated on June 04, 2022

Comments

  • Ryan Sayles
    Ryan Sayles almost 2 years

    I have an app with multiple fragments and I would like to know how to add a background that is different for each fragment. The layout I am using has scrollable tabs which all use the same xml file. I also have a MainActivity that sets the view and an adapter for each fragment. I know you can add a background using the xml file with android:background or something of the sort as well as setting it to the view in the main activity but I can't figure out how to do it to each tab. Thank you for any help!

  • Nazerke
    Nazerke over 10 years
    Hey Andrea,thanks for the answer. Could you please have a look at my question stackoverflow.com/questions/21181193/… I'm having trouble with setting background image, when I do f.getView().setBackgroundResource(R.drawable.image) it doesn't change, similarly when i do f.getView().getBackground() it returns null.