android - 以编程方式创建的视图不继承主题
问题描述
我正在尝试务实地创建一个视图,然后将其添加到我的活动中。这一点工作正常,但是我的新视图没有继承视图组的主题
我的主题:
<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);
解决方案
布局中的android:theme
属性仅在膨胀期间有效,并且仅在该特定子树上有效。它不会应用于Activity
的整体主题。
但是,该属性所做的只是导致LayoutInflater
将其当前Context
与指定的主题包装在 a 中ContextThemeWrapper
。我们可以自己做类似的事情,只是为了说明基本用法:
ContextThemeWrapper wrapper = new ContextThemeWrapper(getContext(), R.style.CustomButtonTheme);
AppCompatButton button = new AppCompatButton(wrapper);
然而,这已经为我们完成了,基本上,当为该属性在内部LayoutInflater
创建一个时。那就是创建will 的,所以我们可以简单地使用它来实例化我们的:ContextThemeWrapper
android:theme
ContextThemeWrapper
Context
LinearLayout
Context
AppCompatButton
AppCompatButton button = new AppCompatButton(buttonArea.getContext());
正如 OP 指出的那样,这具有在几乎所有类似设置中工作的额外好处,而无需知道所需的确切主题。
推荐阅读
- node.js - 在nodejs中安装opencv时出错?
- ios - 在没有系统警报的情况下设置 NEHotspotConfiguration
- python - 从 Python 列表中过滤非英语关键字
- rspec - 页面同时具有可见和不可见的字段
- vb.net - 值不能为空。参数名称:objectType
- ssis - SSIS OLE DB 命令
- angular - 在 Angular 中进行测试的最佳实践是什么?
- angular - 如何使用 Angular CLI 7.0.0-RC2 正确创建库项目
- java - Java 正则表达式是否支持排序序列?
- c++ - 你能专门化 std::unique_lock