2017-02-17 52 views
1

我希望應用程序中的每個文本都是sans-serif-thin,但我不知道如何更改它。我可以將android:fontFamily="sans-serif-thin"添加到TextView,它工作的很好,但我不想在每個活動中更改每個TextView的代碼。如何爲應用程序中的所有文本設置fontFamily?

我試過<item name="android:fontFamily">sans-serif-thin</item>加入AppTheme樣式styles.xml但沒有效果。

+0

已應用該主題?您可以通過在Manifest.xml的''字段中添加'android:theme =「@ style/AppTheme」'來爲整個應用程序應用主題 – Jack

回答

2

如何爲應用程序中的所有文本設置fontFamily?

解決方案

如果你想只使用android-default-font(SANS,襯線,單聲道)。

試試這個。

<style name="AppTheme" parent="AppBaseTheme"> 
    <item name="android:textViewStyle">@style/MyTextViewStyle</item> 
</style> 

<style name="MyTextViewStyle" parent="android:Widget.TextView"> 
    <item name="android:fontFamily">sans-serif-thin</item> 
</style> 

附加

如果要指定一個custom font作爲默認字體,您可以使用Calligraphy庫。該庫提供了與字體相關的各種功能。

+0

是的,這可以工作。 4分鐘,直到我可以接受答案。這是一條非常愚蠢的規則,現在我必須四分鐘停留,而不是完成工作。 – TimSim

0

如果您需要爲android應用程序中的所有TextView設置一種字體,則可以使用此解決方案。它將覆蓋所有TextView的字體,包括操作欄和其他標準組件,但EditText的密碼字體不會被重寫。

public class MyApp extends Application { 

@Override 
public void onCreate() { 
    TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); // font from assets: "assets/fonts/Roboto-Regular.ttf 
} 
} 

不要忘了添加機器人:在清單文件的應用程序標記名稱=「com.you.yourapp.MyApp」。

添加在主題style.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <style name="MyAppTheme" parent="@android:style/Theme.Holo.Light"> 
    <!-- you should set typeface which you want to override with TypefaceUtil --> 
    <item name="android:typeface">serif</item> 
    </style> 
</resources> 

創建一個類TypefaceUtil.java

import android.content.Context; 
import android.graphics.Typeface; 
import android.util.Log; 
import java.lang.reflect.Field; 

public class TypefaceUtil { 

/** 
* Using reflection to override default typeface 
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN 
* @param context to work with assets 
* @param defaultFontNameToOverride for example "monospace" 
* @param customFontFileNameInAssets file name of the font from assets 
*/ 
public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) { 
    try { 
     final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets); 

     final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride); 
     defaultFontTypefaceField.setAccessible(true); 
     defaultFontTypefaceField.set(null, customFontTypeface); 
    } catch (Exception e) { 
     Log.e("Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride); 
    } 
} 
} 
相關問題