Apply theme to button programmatically

岁酱吖の 提交于 2019-12-22 06:49:33

问题


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

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

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"/>

Thanks in advance.


回答1:


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));



回答2:


In case you need to change the theme progamatically and you are using the support library, you could simply use:

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

for TextViews and Buttons. There are similar classes for the rest of Views :-)



来源:https://stackoverflow.com/questions/32277284/apply-theme-to-button-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!