以编程方式将主题应用于按钮

str*_*sub 5 android android-appcompat

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

Button button = new Button(context);
button.setText("Button");
Run Code Online (Sandbox Code Playgroud)

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

在布局中它实现如下:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeBasedOnAppcompatButton"/>
Run Code Online (Sandbox Code Playgroud)

提前致谢.

fra*_*nch 17

您应该使用ContextThemeWrapper,它会更改默认主题.只需像往常一样获取上下文,并使用如下所示:

new Button(new ContextThemeWrapper(context, R.style.my_theme));
Run Code Online (Sandbox Code Playgroud)