以编程方式将主题应用于按钮

Apply theme to button programmatically

是否可以通过编程方式将 Widget.AppCompat.Button 主题应用到按钮?

Button button = new Button(context);
button.setText("Button");

目前,我正在使用自定义可绘制资源来尝试实现类似 AppCompat 主题的样式,但我认为它可能更容易实现。

在布局中实现如下:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeBasedOnAppcompatButton"/>

提前致谢。

您应该使用 ContextThemeWrapper,它会更改默认主题。像往常一样获取上下文,然后像下面这样使用它:

new Button(new ContextThemeWrapper(context, R.style.my_theme));

如果您需要以编程方式更改主题并且您正在使用支持库,您可以简单地使用:

TextViewCompat.setTextAppearance(getContext(), R.style.AppTheme_TextStyle_ButtonDefault_Whatever);

对于 TextView 和按钮。其余的 Views 也有相似的 类 :-)