如何在安卓中为TextView设置样式或字体?

7
我想为TextView中的文本设置样式或字体,就像下面显示的图片一样:
4个回答

12
<TextView
style="@style/CodeFont"
android:text="@string/hello" />

你需要将那段代码的字体样式设置为:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
    </style>
</resources>

直接来自:http://developer.android.com/guide/topics/ui/themes.html

11

你需要一个自定义字体,然后你可以这样做:

Typeface mFont = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
MyTextView.setTypeface(mFont);

您需要在资产文件夹中创建一个“字体”文件夹。将您的字体放入其中。
当然,您也可以创建自定义 TextView 。如果您更喜欢这种方法,请参考我之前给出的此答案

3

如果您想在多个TextView上进行更改,还有另一种方法:使用类:

public class MyTextView extends TextView {

public MyTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public MyTextView(Context context) {
    super(context);
    init();
}

private void init() {
    if (!isInEditMode()) {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Ubuntu-L.ttf");
        setTypeface(tf);
    }
}

}

并且在布局中替换:

<TextView 
...
/>

使用:

<com.WHERE_YOUR_CLASS_IS.MyTextView 
...

/>

0
你可以创建一个 layout.xml 文件,并将你的 textview 放入其中,类似于以下内容:
textView.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
style="@android:style/Holo.ButtonBar" >

如果你不喜欢这个,那么你可以创建自己的样式。就像这样:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="Custom" parent="@android:style/TextAppearance.Large" >
        <item name="android:typeface">monospace</item>
    </style>
</resources>

并在布局文件中将样式更改为类似以下内容:

style="@style/Custom"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接