在 android 中以编程方式设置 TextView 文本外观

我将实现一个 LinearLayout,其中输入字段是根据数据库表的字段数以编程方式生成的。

不幸的是,当我试图在 TextView中将属性: textApperance设置为 textApperanceLarge时,它不起作用。下面是我的密码..。

for (int i = 0; i < selectedProducts; i++) {


premLayout[i] = new LinearLayout(this);
premLayout[i].setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
premLayout[i].setOrientation(LinearLayout.HORIZONTAL);
premLayout[i].setGravity(Gravity.TOP);


premTextView[i] = new TextView(this);
premTextView[i].setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
2.0f));
premTextView[i].setTextAppearance(this, android.R.attr.textAppearanceLarge);


premTextView[i].setText(premiumChannels.get(i));
premTextView[i].setId(i + 600);


int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
premTextView[i].setWidth(px);


premLayout[i].addView(premTextView[i]);
60031 次浏览

像这样用,会有用的。

textView.setTextAppearance(this, android.R.style.TextAppearance_Large);

或者,由于 API 23,您不需要传递上下文,因此,您可以简单地调用:

textView.setTextAppearance(android.R.style.TextAppearance_Large);

如果您希望支持 API 23或更高版本以及更低版本,您可以使用下面的方法来简化您的任务。只有当你的目标是 API 23或更高的时候才使用下面的方法。如果您的目标 API 小于23,下面的代码将出现错误,因为新方法在其中不可用。

public void setTextAppearance(Context context, int resId) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
super.setTextAppearance(context, resId);
} else {
super.setTextAppearance(resId);
}
}

使用 TextViewCompat.setTextAppearance()方法,它将处理您的 sdk 版本检查。