繁体   English   中英

如何在android中将样式或字体设置为TextView的文本?

[英]How to set style or font to text of a TextView in android?

我想在TextView为文本设置样式或字体,如下图所示:

在此输入图像描述

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

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

您必须在assets文件夹中创建“fonts”文件夹。 删除你的字体。
您当然也可以创建自定义TextView 如果您愿意的话,请参考这个答案 ,我给了一会儿。

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

你需要使用codefont样式:

<?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

如果要在许多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 
...

/>

您可以创建一个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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM