Android 如何更改文本视图上的字体?

Android 如何更改文本视图上的字体?,android,fonts,textview,Android,Fonts,Textview,如何更改文本视图中的字体,默认显示为Arial?如何将其更改为Helvetica?首先,默认值不是Arial。默认设置为Droid SAN 其次,要更改为不同的内置字体,请在布局XML中使用android:typeface,或在Java中使用setTypeface() 第三,Android中没有Helvetica字体。内置选项有Droid Sans(Sans)、Droid Sans Mono(monospace)和Droid Serif(Serif)。虽然您可以将自己的字体与应用程序捆绑在一起,

如何更改
文本视图中的字体,默认显示为Arial?如何将其更改为Helvetica?

首先,默认值不是Arial。默认设置为Droid SAN

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

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

编辑

Android设计语言依赖于传统的排版工具 例如比例、空间、节奏以及与基础网格的对齐。 成功部署这些工具对于帮助用户至关重要 快速理解一屏信息。支持使用 在排版方面,冰淇淋三明治引入了一种新的类型,名为 Roboto,专为UI和 高分辨率屏幕

当前的TextView框架提供了轻薄、规则的Roboto 和粗体的重量,以及每个重量的斜体样式。这个 框架还提供了规则和粗体的Roboto压缩变体 权重,以及每个权重的斜体样式

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

编辑2

随着SupportLibrary26的出现,Android现在通过以下方式支持自定义字体: 违约您可以在res/font中插入新字体,这些字体可以单独设置为XML文本视图,也可以通过编程方式设置为文本视图。整个应用程序的默认字体也可以通过定义it styles.xml来更改。android开发者文档对此有明确的指导


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

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

以上答案是正确的。如果您正在使用这段代码,请确保在“资产”文件夹下创建名为“字体”的子文件夹。

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

做一些类似于:

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;

}
}
公共类CustomFontsLoader{
公共静态final int FONT\u NAME\u 1=0;
公共静态final int FONT\u NAME\u 2=1;
公共静态final int FONT\u NAME\u 3=2;
自定义字体的私有静态最终整数=3;
私有静态布尔fontsLoaded=false;
私有静态字体[]字体=新字体[3];
私有静态字符串[]fontPath={
“字体/FONT\u名称\u 1.ttf”,
“字体/FONT\u名称\u 2.ttf”,
“字体/FONT\u名称\u 3.ttf”
};
/**
*返回基于其标识符加载的自定义字体。
* 
*@param context-当前上下文
*@param fontIdentifier=请求字体的标识符
* 
*@返回请求字体的Typeface对象。
*/
公共静态字体getTypeface(上下文上下文,int-fontIdentifier){
如果(!fontsLoaded){
加载字体(上下文);
}
返回字体[fontIdentifier];
}
专用静态void加载字体(上下文){
对于(int i=0;i
这样,您就可以从应用程序中的任何地方获取字体。

有史以来的最佳实践 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;
    }
}
<?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>
attrs.xml:(放置res/values的位置


如何使用:

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

希望这对您有所帮助。

导入java.lang.ref.WeakReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;

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

public class FontsManager {

    private static FontsManager instance;

    private static HashMap<String, WeakReference<Typeface>> typefaces = new HashMap<String, WeakReference<Typeface>>();

    private static Context context;

    private FontsManager(final Context ctx) {
        if (context == null) {
            context = ctx;
        }
    }

    public static FontsManager getInstance(final Context appContext) {
        if (instance == null) {
            instance = new FontsManager(appContext);
        }
        return instance;
    }

    public static FontsManager getInstance() {
        if (instance == null) {
            throw new RuntimeException(
                    "Call getInstance(Context context) at least once to init the singleton properly");
        }
        return instance;
    }

    public Typeface getFont(final String assetName) {
        final WeakReference<Typeface> tfReference = typefaces.get(assetName);
        if (tfReference == null || tfReference.get() == null) {
            final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
                    assetName);
            typefaces.put(assetName, new WeakReference<Typeface>(tf));
            return tf;
        }
        return tfReference.get();
    }

}
导入java.util.HashMap; 导入android.content.Context; 导入android.graphics.Typeface; 公共类FontsManager{ 私有静态FontsManager实例; 私有静态HashMap typefaces=newhashmap(); 私有静态语境; 私有FontsManager(最终上下文ctx){ if(上下文==null){ 上下文=ctx; } } 公共静态FontsManager getInstance(最终上下文appContext){ if(实例==null){ 实例=新FontsManager(appContext); } 返回实例; } 公共静态FontsManager getInstance(){ if(实例==null){ 抛出新的运行时异常( “至少调用一次getInstance(上下文)以正确初始化单例”); } 返回实例; } 公共字体getFont(最终字符串assetName){ final WeakReference tfReference=typefaces.get(assetName); if(tfReference==null | | tfReference.get()==null){ final Typeface tf=Typeface.createFromAsset(context.getResources().getAssets(), 资产名称); 字体。put(assetName,newweakreference(tf)); 返回tf; } 返回tfReference.get(); } }

通过这种方式,您可以创建一个从TextView继承的视图,并在其构造函数上调用setTypeface。

它有点旧,但我对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;
            }   
        }                
    }       
}   
}

从资源中获取字体并设置为所有子项

public static void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"));// "BKOODB.TTF"));
        }
    } catch (Exception e) {
 }
 } 
publicstaticvoidoverridefonts(最终上下文,最终视图v){
试一试{
如果(v)为Vi的实例
public static void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"));// "BKOODB.TTF"));
        }
    } catch (Exception e) {
 }
 } 
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);
  }
}
myTextView = (TextView) findViewById(R.id.myTextView);
Font.PROXIMA_NOVA.apply(this, myTextView);
public class Fonts {
  public static HashSet<String,Typeface> fonts = new HashSet<>();

  public static Typeface get(Context context, String file) {
    if (! fonts.contains(file)) {
      synchronized (this) {
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
        fonts.put(name, typeface);
      }
    }
    return fonts.get(file);
  }
}

// Usage
Typeface myFont = Fonts.get("arial.ttf");
public class FontTextView extends TextView {
    String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};

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

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode()) {
            init(attrs);
        }

    }

    public FontTextView(Context context) {
        super(context);
        if (!isInEditMode()) {
            init(null);
        }
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
            if (a.getString(R.styleable.FontTextView_font_type) != null) {
                String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];

                if (fontName != null) {
                    Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
                    setTypeface(myTypeface);
                }
                a.recycle();
            }
        }
    }
}
<declare-styleable name="FontTextView">
<attr name="font_type" format="enum">
    <enum name="HelveticaNeue" value="0"/>
    <enum name="HelveticaNeueLight" value="1"/>
    <enum name="motschcc" value="2"/>
    <enum name="symbol" value="3"/>
</attr>
<?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>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/my_font"/>
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf"); 
txt.setTypeface(tf);
Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.0.2'
        <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"
        />
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>