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

RAP*_*POS 3 android textview

例如:

TextView textView = new TextView(PhotoActivity.this);
textView.setText("Photo not found.");
Run Code Online (Sandbox Code Playgroud)

如何设置风格?

textView.set... ???
Run Code Online (Sandbox Code Playgroud)

Jor*_*llo 14

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

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


小智 7

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

textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);
Run Code Online (Sandbox Code Playgroud)

  • 这会改变字体,_not_样式. (2认同)

use*_*237 5

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

低于api级别23

setTextAppearance(int res id)
Run Code Online (Sandbox Code Playgroud)

从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
            * /sf/answers/434058901/
            * */
        } else {
            textView.setTextAppearance(R.style.yourTextViewStyleResourceID);
        }
Run Code Online (Sandbox Code Playgroud)

更新

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

TextViewCompat.setTextAppearance(textViewObject, R.style.yourTextViewStyleResourceID);
Run Code Online (Sandbox Code Playgroud)

要给字体样式加粗斜体,建议您检查此答案

  • 作为@JorgeCastillo [notes](http://stackoverflow.com/a/39247670/295028),您可以通过使用TextViewCompat来避免版本检查: (4认同)

RAP*_*POS -1

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

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

作为替代方法:

textView.setGravity(Gravity.CENTER);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

8341 次

最近记录:

8 年,9 月 前