在android中以编程方式设置TextView TextAppeance

在android中以编程方式设置TextView TextAppeance,android,textview,Android,Textview,我将实现一个LinearLayout,其中输入字段是根据数据库表的字段数量以编程方式生成的 不幸的是,当我试图在TextView中将属性:textpearance设置为textpearancelarge时,它不起作用。下面是我的代码 for (int i = 0; i < selectedProducts; i++) { premLayout[i] = new LinearLayout(this); premLayout[i].setLay

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

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

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]);
for(int i=0;i
像这样使用。它会工作的

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);
    }
}
public void settext外观(上下文上下文,int resId){
if(Build.VERSION.SDK_INT
使用
TextViewCompat.setTextAppearance()
方法,该方法将负责您的sdk版本检查。

如果不工作,我假设您的意思是文本只是“正常大小”?默认大小为TextAppearanceSmall…但我想设置…TextAppearanceLarge。您正在构建自己的文本外观属性,或者正在使用android。在您的代码中,您使用的是android。我正在尝试使用android提供的文本外观。非常感谢!它可以工作!我们什么时候使用android.R.attr.TextAppearanceLarge代替android.R.style.TextAppearance\u Large?@RajuGujarati:
android.R.attr.textAppearanceLarge
是一个属性,用于设置当前主题所使用的样式。当您使用自定义主题时,您可以给它任何值。
android.R.style.TextAppearance\u Large
是一种样式,在这种情况下,它恰好是设置为e attr,用于默认主题。此方法在API级别23中已被弃用。请在API 23+中改用setTextAppearance(int)。我在super.setTextAppea…行中遇到以下错误“无法解析方法setTextAppearance(int)”当然,另一个解决方案不是使用monkeypatch setTextAppearance,但如果能够实现这一点,那就太好了working@Arstmean
TextViewCompat.setTextAppearance(@NonNull TextView TextView,@StyleRes int resd)
你如何使用它?我有这个视图。@doctorram这只适用于textview。如果你的视图是textview,那么就使用这个方法-TextViewCompat.settextExearance(你的文本视图在这里,R.style.yourStyle,你想要应用它);