如何改变文本/字体设置在一个Android TextView?

例如,如何使文本加粗?


当前回答

在values文件夹中的style.xml文件中定义一个新的样式,使用您想要的格式

<style name="TextViewStyle" parent="AppBaseTheme">
    <item name="android:textStyle">bold</item>
    <item name="android:typeface">monospace</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#5EADED</item>

</style>

然后通过编写以下带有TextView属性的代码将此样式应用到TextView

style="@style/TextViewStyle"

其他回答

要在layout.xml文件中这样做:

android:textStyle

例子:

android:textStyle="bold|italic"

程序上的方法是:

setTypeface(Typeface tf)

设置应显示文本的字体和样式。注意,并不是所有字体家族都有粗体和斜体变体,所以你可能需要使用setTypeface(Typeface, int)来获得你真正想要的外观。

如果你在画它,那么这个就可以做到:

TextPaint.setFlags(Paint.FAKE_BOLD_TEXT_FLAG);

你可以用这个字体

创建一个类名TypefaceTextView并扩展TextView

私有静态Map mTypefaces;

public TypefaceTextView(final Context context) {
    this(context, null);
}

public TypefaceTextView(final Context context, final AttributeSet attrs) {
    this(context, attrs, 0);
}

public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);
    if (mTypefaces == null) {
        mTypefaces = new HashMap<String, Typeface>();
    }

    if (this.isInEditMode()) {
        return;
    }

    final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
    if (array != null) {
        final String typefaceAssetPath = array.getString(
                R.styleable.TypefaceTextView_customTypeface);

        if (typefaceAssetPath != null) {
            Typeface typeface = null;

            if (mTypefaces.containsKey(typefaceAssetPath)) {
                typeface = mTypefaces.get(typefaceAssetPath);
            } else {
                AssetManager assets = context.getAssets();
                typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
                mTypefaces.put(typefaceAssetPath, typeface);
            }

            setTypeface(typeface);
        }
        array.recycle();
    }
}

将字体粘贴到资源文件夹中创建的字体文件夹中

<packagename.TypefaceTextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1.5"
        android:gravity="center"
        android:text="TRENDING TURFS"
        android:textColor="#000"
        android:textSize="20sp"
        app:customTypeface="fonts/pompiere.ttf" />**here pompiere.ttf is the font name**

将这些行放在xml的父布局中

 xmlns:app="http://schemas.android.com/apk/res/com.mediasters.wheresmyturf"
xmlns:custom="http://schemas.android.com/apk/res-auto"

在使用自定义字体,但没有粗体字体的情况下,可以使用:

myTextView.setText(Html.fromHtml("<b>" + myText + "</b>");
editText.setTypeface(Typeface.createFromAsset(getAssets(), ttfFilePath));
etitText.setTypeface(et.getTypeface(), Typeface.BOLD);

将字体和样式都设置为粗体。