在Android中以编程方式设置TextView的TextAppearance

74

我将实现一个LinearLayout,其中的输入字段将根据数据库表的字段数量在程序中动态生成。

不幸的是,当我尝试在TextView中设置属性:textApperancetextApperanceLarge时,它无法生效。以下是我的代码...

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]);

你所说的“不工作”,是指文本只是“普通大小”吗? - HalR
默认大小是TextAppearanceSmall...但我想设置为TextAppearanceLarge。 - Jeff Bootsholz
你正在构建自己的文本外观属性或者你正在使用 Android 提供的。在你的代码中,你正在使用 Android 的。 - Monty
我正在尝试使用Android提供的文本外观。 - Jeff Bootsholz
2个回答

227

像这样使用。它会起作用。

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

或者,自API 23以来,您不需要传递上下文。因此,您可以直接调用:

或者,自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);
    }
}

3
非常感谢!它有效了! 我们应该在什么情况下使用 android.R.attr.textAppearanceLarge 而不是 android.R.style.TextAppearance_Large? - Jeff Bootsholz
@RajuGujarati: android.R.attr.textAppearanceLarge 是一个属性,用于设置当前主题使用的样式。当您使用自定义主题时,可以为其赋任何值。android.R.style.TextAppearance_Large 是一种样式,在这种情况下它恰好是默认主题中设置给该属性的值。 - njzk2
该方法已在API级别23中被弃用。请使用API 23+中的setTextAppearance(int)代替。 - Sergii
我在使用super.setTextAppearance()的代码行上遇到了以下错误: “Cannot resolve method setTextAppearance(int)” 当然,另一种解决方法是不要使用monkeypatch setTextAppearance,但让它正常工作也是不错的。 - Parsa
使用setTextAppearance(@NonNull TextView textView, @StyleRes int resId)实现向下兼容。 - Arst
7
@Arst 意味着TextViewCompat.setTextAppearance(@NonNull TextView textView, @StyleRes int resId)函数。 - Deni Erdyneev

36

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


你怎么使用它?我有这个视图。 - doctorram
@doctorram 这仅适用于TextView。如果您的视图是TextView,则只需使用此方法 - TextViewCompat.setTextAppearance(your_text_view_here, R.style.yourStyle_which_want_to_apply); - Raghav Sharma
这比被接受的答案简单。 - etomun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接