Android 如何更改 TextView 上的字体?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2888508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:44:51  来源:igfitidea点击:

How to change the font on the TextView?

androidfontstextview

提问by Praveen

How to change the font in a TextView, as default it's shown up as Arial? How to change it to Helvetica?

如何更改 a 中的字体TextView,默认情况下它显示为 Arial?怎么改成Helvetica

回答by CommonsWare

First, the default is not Arial. The default is Droid Sans.

首先,默认值不是 Arial。默认为 Droid Sans。

Second, to change to a different built-in font, use android:typefacein layout XML or setTypeface()in Java.

其次,要更改为不同的内置字体,请android:typeface在布局 XML 或setTypeface()Java 中使用。

Third, there is no Helvetica font in Android. The built-in choices are Droid Sans (sans), Droid Sans Mono (monospace), and Droid Serif (serif). While you can bundle your own fonts with your application and use them via setTypeface(), bear in mind that font files are big and, in some cases, require licensing agreements (e.g., Helvetica, a Linotype font).

第三,Android 中没有 Helvetica 字体。内置选项是 Droid Sans ( sans)、Droid Sans Mono ( monospace) 和 Droid Serif ( serif)。虽然您可以将自己的字体与应用程序捆绑在一起并通过 使用它们setTypeface(),但请记住字体文件很大,并且在某些情况下需要许可协议(例如Helvetica,一种 Linotype 字体)。

EDIT

编辑

The Android design language relies on traditional typographic tools such as scale, space, rhythm, and alignment with an underlying grid. Successful deployment of these tools is essential to help users quickly understand a screen of information. To support such use of typography, Ice Cream Sandwich introduced a new type family named Roboto, created specifically for the requirements of UI and high-resolution screens.

The current TextView framework offers Roboto in thin, light, regular and bold weights, along with an italic style for each weight. The framework also offers the Roboto Condensed variant in regular and bold weights, along with an italic style for each weight.

Android 设计语言依赖于传统的排版工具,例如比例、空间、节奏以及与底层网格的对齐。成功部署这些工具对于帮助用户快速了解信息屏幕至关重要。为了支持这种排版的使用,Ice Cream Sandwich 引入了一个名为 Roboto 的新类型系列,专为 UI 和高分辨率屏幕的要求而创建。

当前的 TextView 框架以细、轻、规则和粗体提供 Roboto,以及每个权重的斜体样式。该框架还提供常规粗体粗体的 Roboto Condensed 变体,以及每个粗体的斜体样式。

After ICS, android includes Roboto fonts style, Read more Roboto

在 ICS 之后,android 包括 Roboto 字体样式,阅读更多Roboto

EDIT 2

编辑 2

With the advent of Support Library 26, Android now supports custom fonts by default. You can insert new fonts in res/fontswhich can be set to TextViews individually either in XML or programmatically. The default font for the whole application can also be changed by defining it styles.xml The android developer documentation has a clear guide on this here

随着支持库 26 的出现,Android 现在默认支持自定义字体。您可以在res/fonts 中插入新字体,这些字体可以在 XML 中或以编程方式单独设置为 TextViews。整个应用程序的默认字体也可以通过定义它的styles.xml 来更改Android 开发人员文档在这里有明确的指南

回答by HjK

First download the .ttffile of the font you need (arial.ttf). Place it in the assetsfolder. (Inside assets folder create new folder named fontsand place it inside it.) Use the following code to apply the font to your TextView:

首先下载.ttf您需要的字体文件 ( arial.ttf)。将其放在 assets文件夹中。(在assets文件夹中创建名为fonts的新文件夹并将其放在其中。)使用以下代码将字体应用于您的TextView

Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); 
textView.setTypeface(type);

回答by Android Girl

Typeface tf = Typeface.createFromAsset(getAssets(),
        "fonts/DroidSansFallback.ttf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);

回答by Daniel L.

You might want to create static classwhich will contain all the fonts. That way, you won't create the font multiple times which might impact badly on performance. Just make sure that you create a sub-foldercalled "fonts" under "assets" folder.

您可能想要创建包含所有字体的静态类。这样,您就不会多次创建可能对性能产生严重影响的字体。只需确保在“ assets”文件夹下创建一个名为“ fonts”的子文件夹。

Do something like:

做类似的事情:

public class CustomFontsLoader {

public static final int FONT_NAME_1 =   0;
public static final int FONT_NAME_2 =   1;
public static final int FONT_NAME_3 =   2;

private static final int NUM_OF_CUSTOM_FONTS = 3;

private static boolean fontsLoaded = false;

private static Typeface[] fonts = new Typeface[3];

private static String[] fontPath = {
    "fonts/FONT_NAME_1.ttf",
    "fonts/FONT_NAME_2.ttf",
    "fonts/FONT_NAME_3.ttf"
};


/**
 * Returns a loaded custom font based on it's identifier. 
 * 
 * @param context - the current context
 * @param fontIdentifier = the identifier of the requested font
 * 
 * @return Typeface object of the requested font.
 */
public static Typeface getTypeface(Context context, int fontIdentifier) {
    if (!fontsLoaded) {
        loadFonts(context);
    }
    return fonts[fontIdentifier];
}


private static void loadFonts(Context context) {
    for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
        fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
    }
    fontsLoaded = true;

}
}

This way, you can get the font from everywhere in your application.

这样,您就可以从应用程序的任何地方获取字体。

回答by Hiren Patel

Best practice ever

最佳实践

TextViewPlus.java:

TextViewPlus.java:

public class TextViewPlus extends TextView {
    private static final String TAG = "TextView";

    public TextViewPlus(Context context) {
        super(context);
    }

    public TextViewPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface typeface = null;
        try {
            typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
        } catch (Exception e) {
            Log.e(TAG, "Unable to load typeface: "+e.getMessage());
            return false;
        }

        setTypeface(typeface);
        return true;
    }
}

attrs.xml:(Where to place res/values)

attrs.xml:(放置res/values 的位置

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TextViewPlus">
        <attr name="customFont" format="string"/>
    </declare-styleable>
</resources>

How to use:

如何使用:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.mypackage.TextViewPlus
        android:id="@+id/textViewPlus1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="@string/showingOffTheNewTypeface"
        foo:customFont="my_font_name_regular.otf">
    </com.mypackage.TextViewPlus>
</LinearLayout>

Hope this will help you.

希望这会帮助你。

回答by VJ Vélan Solutions

The answers above are correct. Just make sure that you create a sub-folder called "fonts" under "assets" folder if you are using that piece of code.

上面的答案是正确的。如果您正在使用那段代码,请确保在“assets”文件夹下创建一个名为“fonts”的子文件夹。

回答by Chris Aitchison

Another way to consolidate font creation...

另一种整合字体创建的方法......

public class Font {
  public static final Font  PROXIMA_NOVA    = new Font("ProximaNovaRegular.otf");
  public static final Font  FRANKLIN_GOTHIC = new Font("FranklinGothicURWBoo.ttf");
  private final String      assetName;
  private volatile Typeface typeface;

  private Font(String assetName) {
    this.assetName = assetName;
  }

  public void apply(Context context, TextView textView) {
    if (typeface == null) {
      synchronized (this) {
        if (typeface == null) {
          typeface = Typeface.createFromAsset(context.getAssets(), assetName);
        }
      }
    }
    textView.setTypeface(typeface);
  }
}

And then to use in your activity...

然后在您的活动中使用...

myTextView = (TextView) findViewById(R.id.myTextView);
Font.PROXIMA_NOVA.apply(this, myTextView);

Mind you, this double-checked locking idiom with the volatile field only works correctly with the memory model used in Java 1.5+.

请注意,这种带有 volatile 字段的双重检查锁定习惯用法仅适用于 Java 1.5+ 中使用的内存模型。

回答by Marek Rze?niczek

Best practice is to use Android Support Library version 26.0.0 or above.

最佳做法是使用 Android 支持库版本 26.0.0 或更高版本。

STEP 1: add font file

STEP 1:添加字体文件

  1. In resfolder create new fontresource dictionary
  2. Add font file (.ttf, .orf)
  1. res文件夹中创建新的字体资源字典
  2. 添加字体文件 ( .ttf, .orf)

For example, when font file will be helvetica_neue.ttf that will generates R.font.helvetica_neue

例如,当字体文件为 helvetica_neue.ttf 时,将生成 R.font.helvetica_neue

STEP 2: create font family

第 2 步:创建字体系列

  1. In fontfolder add new resource file
  2. Enclose each font file, style, and weight attribute in the element.
  1. 字体文件夹中添加新的资源文件
  2. 在元素中包含每个字体文件、样式和粗细属性。

For example:

例如:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
? ? <font
? ? ? ? android:fontStyle="normal"
? ? ? ? android:fontWeight="400"
? ? ? ? android:font="@font/helvetica_neue" />
</font-family>

STEP 3: use it

第 3 步:使用它

In xml layouts:

在 xml 布局中:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/my_font"/>

Or add fonts to style:

或者在样式中添加字体:

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

For more examples you can follow documentation:

有关更多示例,您可以遵循文档:

Working with fonts

使用字体

回答by Alan

It's a little old, but I improved the class CustomFontLoader a little bit and I wanted to share it so it can be helpfull. Just create a new class with this code.

它有点旧,但我对类 CustomFontLoader 进行了一些改进,我想分享它,以便它可以有所帮助。只需使用此代码创建一个新类。

 import android.content.Context;
 import android.graphics.Typeface;

public enum FontLoader {

ARIAL("arial"),
TIMES("times"),
VERDANA("verdana"),
TREBUCHET("trbuchet"),
GEORGIA("georgia"),
GENEVA("geneva"),
SANS("sans"),
COURIER("courier"),
TAHOMA("tahoma"),
LUCIDA("lucida");   


private final String name;
private Typeface typeFace;


private FontLoader(final String name) {
    this.name = name;

    typeFace=null;  
}

public static Typeface getTypeFace(Context context,String name){
    try {
        FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
        if(item.typeFace==null){                
            item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");                 
        }           
        return item.typeFace;
    } catch (Exception e) {         
        return null;
    }                   
}
public static Typeface getTypeFace(Context context,int id){
    FontLoader myArray[]= FontLoader.values();
    if(!(id<myArray.length)){           
        return null;
    } 
    try {
        if(myArray[id].typeFace==null){     
            myArray[id].typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+myArray[id].name+".ttf");                       
        }       
        return myArray[id].typeFace;    
    }catch (Exception e) {          
        return null;
    }   

}

public static Typeface getTypeFaceByName(Context context,String name){      
    for(FontLoader item: FontLoader.values()){              
        if(name.equalsIgnoreCase(item.name)){
            if(item.typeFace==null){
                try{
                    item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
                }catch (Exception e) {          
                    return null;
                }   
            }
            return item.typeFace;
        }               
    }
    return null;
}   

public static void loadAllFonts(Context context){       
    for(FontLoader item: FontLoader.values()){              
        if(item.typeFace==null){
            try{
                item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
            }catch (Exception e) {
                item.typeFace=null;
            }   
        }                
    }       
}   
}

Then just use this code on you textview:

然后在你的 textview 上使用这个代码:

 Typeface typeFace=FontLoader.getTypeFace(context,"arial");  
 if(typeFace!=null) myTextView.setTypeface(typeFace);

回答by Shamsul Arefin Sajib

I finally got a very easy solution to this.

我终于得到了一个非常简单的解决方案。

  1. use these Support libraries in app level gradle,

    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    
  2. then create a directory named "font"inside the resfolder

  3. put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]
  4. After that, reference that font from xmllike this

            <Button
            android:id="@+id/btn_choose_employee"
            android:layout_width="140dp"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:background="@drawable/rounded_red_btn"
            android:onClick="btnEmployeeClickedAction"
            android:text="@string/searching_jobs"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:fontFamily="@font/times_new_roman_test"
            />
    
  1. 应用程序级别的 gradle 中使用这些支持库,

    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    
  2. 然后在res文件夹中创建一个名为“font”的目录

  3. 将 fonts(ttf) 文件放在该字体目录中,记住命名约定 [egname 不应包含任何特殊字符、任何大写字符和任何空格或制表符]
  4. 之后,像这样从xml引用该字体

            <Button
            android:id="@+id/btn_choose_employee"
            android:layout_width="140dp"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:background="@drawable/rounded_red_btn"
            android:onClick="btnEmployeeClickedAction"
            android:text="@string/searching_jobs"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:fontFamily="@font/times_new_roman_test"
            />
    

In this example, times_new_roman_testis a font ttf file from that font directory

在此示例中,times_new_roman_test是来自该字体目录的字体 ttf 文件