【问题标题】:Fontfamily doesn't work on Android LollipopFontfamily 不适用于 Android Lollipop
【发布时间】:2014-11-26 19:19:14
【问题描述】:

我想在我的应用程序中将 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 并未应用于每个视图。例如,ActivityMain.java 中的 TextViews 以我想要的字体显示,但在 SecondActivity.java 等其他活动中,所有 TextViews 都正常显示。如果我在装有 Android 4.1 的设备上运行我的应用程序,它可以在每个视图中运行。我究竟做错了什么?在此先感谢:)

【问题讨论】:

    标签: android android-5.0-lollipop typeface font-family android-fonts


    【解决方案1】:

    如果使用 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");
    }
    }
    

    【讨论】:

    • 那么,这是 Lollipop 中的错误吗?
    猜你喜欢
    • 2015-06-28
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多