Apply theme to button programmatically

Can I apply Widget.AppCompat.Button to a button programmatically?

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

I am currently using a custom resource that is trying to implement a style, such as the AppCompat theme, but I think it might be easier.

In the layout, it implements as:

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

Thanks in advance.

+4
source share
2 answers

You should use ContextThemeWrapper , which changes the default theme. Just get the context as usual and use it as shown below:

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

If you need to change the theme progamatically, and you use the support library, you can simply use:

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

. : -)

0

All Articles