至于TextView,以编程方式更改样式?

时间:2016-01-19 06:03:01

标签: android textview

例如:

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

如何设置样式?

textView.set... ???

5 个答案:

答案 0 :(得分:13)

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

应用它。

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

答案 1 :(得分:7)

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

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

答案 2 :(得分:4)

您可以使用setTextAppearance / setTextAppearance

更改TextView样式

低于api等级23

setTextAppearance(int res id)

来自api level 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);

要给出字体样式Bold Italic,我建议您检查this answer

答案 3 :(得分:1)

您可以使用以下链接:

How to change a TextView's style at runtime

Set TextView style (bold or italic)

祝你好运。

答案 4 :(得分:0)

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

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