以编程方式将主题应用于按钮 [英] Apply theme to button programmatically

查看:48
本文介绍了以编程方式将主题应用于按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to apply Widget.AppCompat.Button theme to button programmatically?

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

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

Currently, I am using custom drawable resource that tries to implement a style like a AppCompat theme, but I think it might be implemented easier.

在布局中,其实现方式如下:

In the layout it implements like:

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

谢谢.

推荐答案

您应使用 ContextThemeWrapper ,它将更改默认主题.只需像平常一样获取上下文,并按如下所示使用它即可:

You should use ContextThemeWrapper, which changes the default theme. Just get a context as you normally would, and use it like below:

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

这篇关于以编程方式将主题应用于按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆