首页 > 解决方案 > 以编程方式创建的视图不继承主题

问题描述

我正在尝试务实地创建一个视图,然后将其添加到我的活动中。这一点工作正常,但是我的新视图没有继承视图组的主题

我的主题:

<style name="CustomButtonTheme" parent="@style/Widget.AppCompat.Button">
  <item name="android:textColor">#FF0000</item>
  <item name="android:background">#00FF00</item>
</style>

我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/buttonArea"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:theme="@style/CustomButtonTheme">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This button inherits CustomButtonTheme" />
</LinearLayout>

Java 代码

AppCompatButton button = new AppCompatButton(getContext());
button.setText("This button does not inherit CustomButtonTheme");

LinearLayout buttonArea = findViewById<LinearLayout>(R.id.buttonArea);
buttonArea.addView(button);

标签: androidandroid-themeandroid-styles

解决方案


布局中的android:theme属性仅在膨胀期间有效,并且仅在该特定子树上有效。它不会应用于Activity的整体主题。

但是,该属性所做的只是导致LayoutInflater将其当前Context与指定的主题包装在 a 中ContextThemeWrapper。我们可以自己做类似的事情,只是为了说明基本用法:

ContextThemeWrapper wrapper = new ContextThemeWrapper(getContext(), R.style.CustomButtonTheme);
AppCompatButton button = new AppCompatButton(wrapper);

然而,这已经为我们完成了,基本上,当为该属性在内部LayoutInflater创建一个时。那就是创建will 的,所以我们可以简单地使用它来实例化我们的:ContextThemeWrapperandroid:themeContextThemeWrapperContextLinearLayoutContextAppCompatButton

AppCompatButton button = new AppCompatButton(buttonArea.getContext());

正如 OP 指出的那样,这具有在几乎所有类似设置中工作的额外好处,而无需知道所需的确切主题。


推荐阅读