首先,您不需要使用布局充气器来创建简单的 Button。你可以只使用:
button = new Button(context);
如果您想设置按钮的样式,您有两种选择:最简单的一种是仅指定代码中的所有元素,就像许多其他答案所建议的那样:
button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
另一种选择是在 XML 中定义样式,并将其应用到按钮。在一般情况下,您可以使用ContextThemeWrapper http://developer.android.com/reference/android/view/ContextThemeWrapper.html为了这:
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 http://developer.android.com/reference/android/widget/TextView.html#setTextAppearance%28android.content.Context,%20int%29.