如何在 android 中设置包含背景颜色

How to set include background color in android

如何在 Android 中设置 include 标签的背景颜色?这不起作用:

 <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%"/>

You can not give a background color into include tag.

为什么?

很明显,如果您能够为 include 标签提供背景颜色,那么它就会被您的 include 颜色和可能应用于该 [=] 的另一种颜色搞得一团糟13=] 已经包含了 .

但是,您也可以通过在标记中指定它们来覆盖包含的布局根视图的所有布局参数(任何 android:layout_* 属性)。 (引用自 https://developer.android.com/training/improving-layouts/reusing-layouts.html#Includ

试试这个:

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

在偏好类别布局中:

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

否则运行时间会发生变化

preference_category.setBackgroundResource(R.id.bckResource);

如果您不是 "too-deep-view-tree-paranoia" 类型的人,您可以 将您的 include 包裹在 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>

编辑:当然,不要忘记先从 preference_category.xml 布局中删除 android:background

对我来说 android:background="@color/colorSecondary"<include> 标签工作正常