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

标签 android styles

我使用以下代码从 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 .

关于android - 如何以编程方式在 View 中设置样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2016249/

相关文章:

wpf - 如何找出应用于控件的样式?

android - 长按矩形

android - ADB 命令仅列出设备上正在运行的应用程序的数量

javascript - 从 android 连接到 node.js 服务器时遇到问题

android - 如何在 Android 应用程序中绘制股票历史图表?

android - 如何更改 Android 5.0 的 DatePicker 对话框颜色

javascript - 命名 Promise 变量等于回调参数

wpf - 为什么我不能在样式内设置数据模板,但可以在控件模板内设置?

android - 如何为 Android ListView 项目创建滑出选项菜单?

没有目标类型的WPF样式?