如何更改TextView上的字体?

Pra*_*een 280 fonts android textview

如何更改a中的字体TextView,默认显示为Arial?如何将其更改为Helvetica

Com*_*are 338

首先,默认值不是Arial.默认是Droid Sans.

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

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

编辑

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

目前的TextView框架为轻量级,轻型,常规和大胆的重量提供了Roboto,并为每个重量提供了斜体样式.该框架还提供Roboto Condensed变体的常规和大胆的重量,以及每个重量的斜体样式.

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

编辑2

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

  • 无法在XML中设置字体?为什么? (6认同)
  • @Jonny你其实可以.您正在创建一个扩展TextView的类,并从构造函数中调用setTypeface. (5认同)
  • @usman:你需要一个第三方库,比如书法:https://github.com/chrisjenx/Calligraphy (2认同)

HjK*_*HjK 253

首先下载所需.ttf字体的文件(arial.ttf).将它放在 assets 文件夹中.(内部资源文件夹创建名为fonts的新文件夹并将其放入其中.)使用以下代码将字体应用于TextView:

Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); 
textView.setTypeface(type);
Run Code Online (Sandbox Code Playgroud)

  • 对于那些使用Android Studio并且找不到"资产"文件夹的人,请参阅[此问题](http://stackoverflow.com/questions/18302603/where-to-place-assets-folder-in-android-studio) .简答:`src/main/assets/fonts /`. (10认同)
  • 亲爱的@lonelearner你可以在http://www.1001freefonts.com/下载免费字体(.ttf)文件或只是google"免费字体" (3认同)

And*_*irl 50

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


Dan*_* L. 32

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

做类似的事情:

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;

}
}
Run Code Online (Sandbox Code Playgroud)

这样,您就可以从应用程序的任何位置获取字体.


Hir*_*tel 19

最好的做法

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TextViewPlus">
        <attr name="customFont" format="string"/>
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

如何使用:

<?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>
Run Code Online (Sandbox Code Playgroud)

希望这会帮助你.


VJ *_*ons 17

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


Chr*_*son 14

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

myTextView = (TextView) findViewById(R.id.myTextView);
Font.PROXIMA_NOVA.apply(this, myTextView);
Run Code Online (Sandbox Code Playgroud)

请注意,这个带有volatile字段的双重检查锁定习惯只能与Java 1.5+中使用的内存模型一起正常工作.


小智 12

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

第1步:添加字体文件

  1. res文件夹中创建新的字体资源字典
  2. 添加字体文件(.ttf,.orf)

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

第2步:创建字体系列

  1. font文件夹中添加新资源文件
  2. 将元素中的每个字体文件,样式和权重属性括起来.

例如:

<?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>
Run Code Online (Sandbox Code Playgroud)

第3步:使用它

在xml布局中:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/my_font"/>
Run Code Online (Sandbox Code Playgroud)

或者将字体添加到样式:

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>
Run Code Online (Sandbox Code Playgroud)

有关更多示例,您可以按照文档:

使用字体


Ala*_*lan 7

它有点旧,但我改进了类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;
            }   
        }                
    }       
}   
}
Run Code Online (Sandbox Code Playgroud)

然后在textview上使用此代码:

 Typeface typeFace=FontLoader.getTypeFace(context,"arial");  
 if(typeFace!=null) myTextView.setTypeface(typeFace);
Run Code Online (Sandbox Code Playgroud)


Pan*_*lan 7

当您的字体存储在里面时,请res/asset/fonts/Helvetica.ttf使用以下内容:

Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf"); 
txt.setTypeface(tf);
Run Code Online (Sandbox Code Playgroud)

或者,如果您的字体文件存储在内部,请res/font/helvetica.ttf使用以下内容:

Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,正在寻找 res 文件夹中的部分! (2认同)

Sha*_*jib 5

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

  1. app level gradle中使用这些支持库,

    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    
    Run Code Online (Sandbox Code Playgroud)
  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"
            />
    
    Run Code Online (Sandbox Code Playgroud)

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