【问题标题】:Apply theme to button programmatically以编程方式将主题应用于按钮
【发布时间】:2016-09-26 20:59:57
【问题描述】:

是否可以以编程方式将 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"/>

提前致谢。

【问题讨论】:

    标签: android android-appcompat


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我认为我实现动态布局的方式是错误的。我将用 listview 适配器替换它。
    【解决方案2】:

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

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

    用于文本视图和按钮。其余视图也有类似的类:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2017-11-06
      相关资源
      最近更新 更多