Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply theme to button programmatically

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.

like image 475
str.gsub Avatar asked Aug 28 '15 18:08

str.gsub


2 Answers

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));
like image 98
fractalwrench Avatar answered Oct 12 '22 00:10

fractalwrench


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

like image 26
cesards Avatar answered Oct 12 '22 00:10

cesards