【问题标题】:As for the TextView, programmatically change the style?至于TextView,以编程方式更改样式?
【发布时间】:2016-04-24 11:59:09
【问题描述】:

例如:

TextView textView = new TextView(PhotoActivity.this);
textView.setText("Photo not found.");

如何设置样式?

textView.set... ???

【问题讨论】:

标签: android textview


【解决方案1】:

您可以使用 setTextAppearance / setTextAppearance 更改 TextView 样式

对于低于 api 级别 23

setTextAppearance(int res id)

从 api 级别 23

setTextAppearance (Context context, int resId)


TextView textView = new TextView(PhotoActivity.this);
        textView.setText("Photo not found.");
        if (Build.VERSION.SDK_INT > 22) {
            textView.setTextAppearance(PhotoActivity.this, R.style.yourTextViewStyleResourceID);
            /*
            * To give font style Bold Italic I would suggest you check this answer
            * https://stackoverflow.com/a/6200841
            * */
        } else {
            textView.setTextAppearance(R.style.yourTextViewStyleResourceID);
        }

更新

也可以在不检查 sdk 版本的情况下赋予样式

TextViewCompat.setTextAppearance(textViewObject, R.style.yourTextViewStyleResourceID);

要给字体样式加粗斜体,我建议你检查this answer

【讨论】:

  • 作为@JorgeCastillo notes,您可以使用TextViewCompat避免版本检查:TextViewCompat.setTextAppearance(statusLinkTextView, R.style.YourTextAppearanceStyle);
【解决方案2】:

对于样式,您可以使用以下选项:

textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);

【讨论】:

  • 这应该是公认的答案。这是最简单有效的。
  • 这会改变字体,不是样式。
【解决方案3】:

谢谢大家,我找到了我需要的解决方案。

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;

TextView textView = new TextView(PhotoActivity.this);
textView.setText("Photo not found.");
textView.setTextColor(Color.WHITE);
textView.setLayoutParams(params);

作为替代方式:

textView.setGravity(Gravity.CENTER);

【讨论】:

  • 如果这是您的答案和解决方案,而不是“如何动态设置 TextColor?”而不是如何设置样式?
  • 在哪个 multiverse 中会更改样式,如“至于 TextView,以编程方式更改样式?”中所述。 ??????
【解决方案4】:

您可以使用以下链接:

How to change a TextView's style at runtime

Set TextView style (bold or italic)

祝你好运。

【讨论】:

    【解决方案5】:

    要以编程方式设置 TextView 样式,您必须具有继承 TextAppearance 样式的样式,并且可以使用以下方法应用它:

    TextViewCompat.setTextAppearance(statusLinkTextView, R.style.YourTextAppearanceStyle);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2017-12-02
      • 2016-07-03
      • 1970-01-01
      相关资源
      最近更新 更多