android - 如何以编程方式在 View 中设置样式属性

我使用以下代码从 XML 中获取 View :

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);

我想为按钮设置一个“样式”,我该如何在 java 中做到这一点,因为我想为我将使用的每个按钮使用多种样式。

最佳答案

首先,您不需要使用布局充气器来创建简单的 Button。您可以使用:

button = new Button(context);

如果您想为按钮设置样式,您有 2 种选择:最简单的一种是仅指定代码中的所有元素,就像许多其他答案所建议的那样:

button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

另一个选项是在 XML 中定义样式,并将其应用于按钮。在一般情况下,您可以使用 ContextThemeWrapper为此:

ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
button = new Button(newContext);

要更改 TextView(或其子类,如 Button)上的文本相关属性,有一个特殊的方法:

button.setTextAppearance(R.style.MyTextStyle);

或者,如果您需要支持 API-23 (Android 6.0) 之前的设备

button.setTextAppearance(context, R.style.MyTextStyle);

此方法不能用于更改所有属性;例如,要更改填充,您需要使用 ContextThemeWrapper。但对于文本颜色、大小等,您可以使用 setTextAppearance .

https://stackoverflow.com/questions/2016249/

相关文章:

android - 如何使用 HTML 5 创建一个安卓应用程序

android - Html 列表标签在 android textview 中不起作用。我能做些什么

android - 使用按钮背景颜色为我的按钮添加波纹效果?

android - 无法修改 ListView 中的 ArrayAdapter : Unsuppor

android - 如何检查 Activity 是在前台还是在可见背景中?

android - 如何检测Android中布局的方向变化?

android - 在 Android 中删除 SQLite 中的行

android - 如何在 Activity 启动时在 ScrollView 中滚动到底部

android - 同步 ScrollView 滚动位置 - android

android - 为什么一个 Android Studio 项目中有两个 build.gradle