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!
Asked
Active
Viewed 1.3k times
2

Ryan Sayles
- 3,389
- 11
- 56
- 79
-
When you create those tab fragments, pass to them through a `Bundle` a int value or something else indicating the target background. You could then use `getArguments()` in the `onCreateView()` method to see what value was passed in and set the proper background. – user Jul 15 '13 at 12:17
-
I don't understand your question: you want to change layout on Fragment or on Tab? Maybe posting your layout (or an image) will be more helpful. – JJ86 Jul 17 '13 at 08:29
-
I want each fragment to have a different background, so that when you either swipe or press a different tab the background of the whole page changes – Ryan Sayles Jul 17 '13 at 11:46
2 Answers
7
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
.
0
You can get the root View of the fragment with the Fragment getView() method. Then you can set the background of the View using one of the setBackground() methods of the View. For example to set a random background color to each fragment:
for ( Fragment f : fragments ) {
f.getView().setBackgroundColor ( (new Random()).nextInt() );
}
PS: I never used fragments, therefore my answer could be wrong.

Andrea Carron
- 1,001
- 13
- 22
-
Hey Andrea,thanks for the answer. Could you please have a look at my question http://stackoverflow.com/questions/21181193/changing-background-image-of-current-fragment-in-viewpager#comment31893915_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. – Nazerke Jan 17 '14 at 15:21