How to set include background color in android

2020-08-22 12:55发布

问题:

How to set background color on an include tag in Android? This does not work:

 <include
 android:id="@+id/list_item_section_text"
 android:layout_width="fill_parent"
 android:layout_height="match_parent"
 layout="@android:layout/preference_category"
 android:background="%MY_BACKGROUND%"/>

回答1:

You can not give a background color into include tag.

Why ?

Its obvious , if you could able to give the background color to include tag then it would be all messed up with your include color and another color which might be applied to that layout which has already included .



回答2:

If you are not "too-deep-view-tree-paranoia" type of guy, you can wrap your include in FrameLayout:

<FrameLayout
    android:id="@+id/list_item_section_text"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="%YOUR_BACKGROUND%">

        <include layout="@android:layout/preference_category"/>

</FrameLayout>

EDIT: Of course, don't forget to remove android:background from your preference_category.xml layout first.



回答3:

Try this:

<include
    android:id="@+id/list_item_section_text"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    layout="@android:layout/preference_category"/>

in preference category layout:

<LinearLayout
    android:id="@+id/preference_category"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="@colors/white"/>

otherwise changes in RUNTIME

preference_category.setBackgroundResource(R.id.bckResource);