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