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!
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
.
回答2:
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.