我想在我的应用程序中将 sans-serif light 设置为默认字体。我正在开发 Android Lollipop 设备。所以,这是我的 styles.xml:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Material.Light.DarkActionBar">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="android:textViewStyle">@style/RobotoTextViewStyle</item>
<item name="android:buttonStyle">@style/RobotoButtonStyle</item>
</style>
<style name="RobotoTextViewStyle" parent="android:Widget.TextView">
<item name="android:fontFamily">sans-serif-light</item>
</style>
<style name="RobotoButtonStyle" parent="android:Widget.Button">
<item name="android:fontFamily">sans-serif-light</item>
</style>
</resources>
当我在我的设备上运行该应用程序时,sans-serif-light 并未应用于每个 View 。例如,ActivityMain.java 中的 TextViews 以我想要的字体显示,但在 SecondActivity.java 等其他 Activity 中,所有 TextViews 都正常显示。如果我在装有 Android 4.1 的设备上运行我的应用程序,它可以在每个 View 中运行。我究竟做错了什么?提前致谢:)
最佳答案
如果使用 Material Design 主题对你来说不重要,你可以使用这个:
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">sans-serif-light</item>
</style>
如果使用 Material Theme 对您的应用很重要,您可以使用以下技术:
import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
现在重载应用程序类中的默认字体
public final class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "SANS_SERIF", "sans_serif_light.ttf");
}
}
关于android - Fontfamily 不适用于 Android Lollipop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27157211/