简体   繁体   中英

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

I want to set style or font to the text in a TextView like the image shown below:

在此输入图像描述

You need a custom font and then you can do this:

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

You have to create a "fonts" folder in your assets folder. Drop your font in there.
You could also create a custom TextView of course. Refer to this answer , I gave a while back, if you prefer that.

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

You need to Make that codefont style:

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

Straight from : http://developer.android.com/guide/topics/ui/themes.html

There is another way if you want to change it on many TextViews, Use a class:

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

}

and in the Layout replace:

<TextView 
...
/>

With:

<com.WHERE_YOUR_CLASS_IS.MyTextView 
...

/>

You could create a layout.xml file that would have your textview in it. Something like :

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

If you dont want this then you could create your custom style. Something like this :

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

and in the layout file change the style to something like :

style="@style/Custom"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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