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

Raj*_*epe 59 android textview

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

不幸的是,当我尝试设置属性时:textApperancetextApperanceLargeTextView,它不起作用.以下是我的代码......

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]);
Run Code Online (Sandbox Code Playgroud)

Hom*_*mam 192

像这样使用.它会工作.

textView.setTextAppearance(this, android.R.style.TextAppearance_Large);
Run Code Online (Sandbox Code Playgroud)

或者,从API 23开始,您不需要传递上下文.因此,您可以简单地致电:

textView.setTextAppearance(android.R.style.TextAppearance_Large);
Run Code Online (Sandbox Code Playgroud)

如果要支持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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Arst表示`TextViewCompat.setTextAppearance(@NonNull TextView textView,@ StyleRes int resId)` (7认同)
  • 非常感谢!有用 !什么时候我们应该使用android.R.attr.textAppearanceLarge而不是android.R.style.TextAppearance_Large? (3认同)

Rag*_*rma 14

使用TextViewCompat.setTextAppearance()将照顾您的SDK版本检查的方法。