如何在DrawerLayout和NavigationView中使用自定义字体

6

我想使用Android的DrawerLayoutNavigationView来创建菜单,但是我不知道如何让菜单项使用自定义字体。是否有人有成功的实现方法?


4
请查看此帖子: https://dev59.com/o10a5IYBdhLWcg3wJVvv 该帖介绍如何将自定义字体应用到NavigationView的项目中。 - Bubu
@Bubu,谢谢你,我亲爱的朋友。 - ydstsh
4个回答

4
Omar Mahmoud的答案可以解决问题。但是它没有利用字体缓存,这意味着您不断地从磁盘中读取,速度很慢。而且显然旧设备可能会泄漏内存 - 尽管我还没有确认这一点。至少,这非常低效。
如果您只想进行字体缓存,请按照步骤1-3进行。这是必须要做的。但是让我们超越这个:让我们实现一个使用Android的Data Binding库(感谢Lisa Wray)的解决方案,以便您可以在布局中添加自定义字体,仅需一个命令。哦,我提到了吗?您不需要扩展TextView*或任何其他Android类。这需要一些额外的工作,但从长远来看,它会使您的生活变得非常轻松。
第1步:在您的Activity中
这是您的Activity应该看起来的样子:
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FontCache.getInstance().addFont("custom-name", "Font-Filename");

    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
    Menu menu = navigationView.getMenu();
    for (int i = 0; i < menu.size(); i++)
    {
        MenuItem menuItem = menu.getItem(i);
        if (menuItem != null)
        {
            SpannableString spannableString = new SpannableString(menuItem.getTitle());
            spannableString.setSpan(new TypefaceSpan(FontCache.getInstance(), "custom-name"), 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            menuItem.setTitle(spannableString);

            // Here'd you loop over any SubMenu items using the same technique.
        }
    }
}

步骤 2:自定义 TypefaceSpan

这个步骤并不复杂。它基本上提取了 Android 的 TypefaceSpan 的所有相关部分,但没有对其进行扩展。它可能应该被命名为其他名称:

 /**
  * Changes the typeface family of the text to which the span is attached.
  */
public class TypefaceSpan extends MetricAffectingSpan
{
    private final FontCache fontCache;
    private final String fontFamily;

    /**
     * @param fontCache An instance of FontCache.
     * @param fontFamily The font family for this typeface.  Examples include "monospace", "serif", and "sans-serif".
     */
    public TypefaceSpan(FontCache fontCache, String fontFamily)
    {
        this.fontCache = fontCache;
        this.fontFamily = fontFamily;
    }

    @Override
    public void updateDrawState(TextPaint textPaint)
    {
        apply(textPaint, fontCache, fontFamily);
    }

    @Override
    public void updateMeasureState(TextPaint textPaint)
    {
        apply(textPaint, fontCache, fontFamily);
    }

    private static void apply(Paint paint, FontCache fontCache, String fontFamily)
    {
        int oldStyle;

        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }

        Typeface typeface = fontCache.get(fontFamily);
        int fake = oldStyle & ~typeface.getStyle();

        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(typeface);
    }
}

现在,我们不必在这里传递FontCache的实例,但如果您想对此进行单元测试,那么我们需要传递。我们都会写单元测试,对吧?我不会。因此,如果有人想纠正我并提供更可测试的实现,请随时提出!

步骤3:添加Lisa Wray库的部分内容

如果这个库被打包起来,我们就可以直接在build.gradle中引用它了,这会很好。但是,它没有太多的东西,所以这不是一个大问题。您可以在GitHub 这里找到它。为了使用这个实现,我将包括所需的部分内容,以防她将项目删除。您还需要添加另一个类来在布局中使用数据绑定,但我将在第4步中介绍:

您的Activity类:

public class Application extends android.app.Application
{
    private static Context context;

    public void onCreate()
    {
        super.onCreate();

        Application.context = getApplicationContext();
    }

    public static Context getContext()
    {
        return Application.context;
    }
}

FontCache类:

/**
 * A simple font cache that makes a font once when it's first asked for and keeps it for the
 * life of the application.
 *
 * To use it, put your fonts in /assets/fonts.  You can access them in XML by their filename, minus
 * the extension (e.g. "Roboto-BoldItalic" or "roboto-bolditalic" for Roboto-BoldItalic.ttf).
 *
 * To set custom names for fonts other than their filenames, call addFont().
 *
 * Source: https://github.com/lisawray/fontbinding
 *
 */
public class FontCache {

    private static String TAG = "FontCache";
    private static final String FONT_DIR = "fonts";
    private static Map<String, Typeface> cache = new HashMap<>();
    private static Map<String, String> fontMapping = new HashMap<>();
    private static FontCache instance;

    public static FontCache getInstance() {
        if (instance == null) {
            instance = new FontCache();
        }
        return instance;
    }

    public void addFont(String name, String fontFilename) {
        fontMapping.put(name, fontFilename);
    }

    private FontCache() {
        AssetManager am = Application.getContext().getResources().getAssets();
        String fileList[];
        try {
            fileList = am.list(FONT_DIR);
        } catch (IOException e) {
            Log.e(TAG, "Error loading fonts from assets/fonts.");
            return;
        }

        for (String filename : fileList) {
            String alias = filename.substring(0, filename.lastIndexOf('.'));
            fontMapping.put(alias, filename);
            fontMapping.put(alias.toLowerCase(), filename);
        }
    }

    public Typeface get(String fontName) {
        String fontFilename = fontMapping.get(fontName);
        if (fontFilename == null) {
            Log.e(TAG, "Couldn't find font " + fontName + ". Maybe you need to call addFont() first?");
            return null;
        }
        if (cache.containsKey(fontFilename)) {
            return cache.get(fontFilename);
        } else {
            Typeface typeface = Typeface.createFromAsset(Application.getContext().getAssets(), FONT_DIR + "/" + fontFilename);
            cache.put(fontFilename, typeface);
            return typeface;
        }
    }
}

这就是全部内容了。

注意:我非常注重我的方法名称。在这里,我已将getApplicationContext()重命名为getContext()。如果您从这里和她的项目中复制代码,请记住这一点。

第四步:可选项:使用数据绑定在布局中自定义字体

以上所有内容都只是实现了一个FontCache。有很多单词。我是一个偏爱冗长的人。除非你做到这一点,否则这个解决方案不会真正变得很酷:

我们需要更改Activity,以便在调用setContentView之前将自定义字体添加到缓存中。此外,setContentViewDataBindingUtil.setContentView替换:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    FontCache.getInstance().addFont("custom-name", "Font-Filename");
    DataBindingUtil.setContentView(this, R.layout.activity_main);

    [...]
}

接下来,添加一个Bindings类。这将把绑定与XML属性关联起来:
/**
 * Custom bindings for XML attributes using data binding.
 * (http://developer.android.com/tools/data-binding/guide.html)
 */
public class Bindings
{
    @BindingAdapter({"bind:font"})
    public static void setFont(TextView textView, String fontName)
    {
        textView.setTypeface(FontCache.getInstance().get(fontName));
    }
}

最后,在您的布局中,执行以下操作:
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <data/>

    <TextView
        [...]
        android:text="Words"
        app:font="@{`custom-name`}"/>

就是这样!说真的:app:font="@{``custom-name``}"。就这样。

关于数据绑定的说明

在撰写本文时,数据绑定文档有点误导人。它们建议在build.gradle中添加一些东西,但这些东西在最新版本的Android Studio中根本行不通。忽略与gradle相关的安装建议,改为执行以下操作:

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0-beta1'
    }
}

android {
    dataBinding {
        enabled = true
    }
}

这种方法几乎让我的应用程序死得很慢。各位要避免它。#无恶意 - Harry Sharma
可以解释一下为什么吗?在去年12月我参加的一次会议上,Google的Android团队专门提到了Lisa Wray方法。 - Michael De Soto
我按照你在这里提到的所有步骤来实现它...是的,它起作用了...但它却影响了我的流畅度...导航抽屉开始闪烁。所以我把它移除了,并为每个导航视图项加载字体...然后它就很好地工作了.. :) - Harry Sharma
我认为问题的一部分是字体缓存没有正常工作。在获取时,缓存会按字体名称查询。在放置时,缓存会按文件名存储。这里有一个开放的 PR:https://github.com/lisawray/fontbinding/pull/4 - Michael De Soto

4

步骤1: 创建样式:

<style name="ThemeOverlay.AppCompat.navTheme">
    <item name="colorPrimary">@android:color/transparent</item>
    <item name="colorControlHighlight">?attr/colorAccent</item>
    <item name="fontFamily">@font/metropolis</item>
</style>

步骤2:在xml中为NavigationView添加主题。

app:theme="@style/ThemeOverlay.AppCompat.navTheme"

如果有人在这里寻找简单的解决方案


这个可以运行,但是它会使导航视图中的所有字体都相同。如果您想在标题和选项菜单中使用不同的字体,该怎么办? - SMBiggs
尝试直接在xml中向DrawerLayout添加样式。 - SABANTO

3

在你的抽屉中使用这种方法传递基本视图

 public static void overrideFonts(final Context context, final View v) {
    Typeface typeface=Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.fontName));
    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);
        }
    } catch (Exception e) {
    }
}

在方法调用时必须传递哪个视图? - Seasia Creative Crew
你应该传递父视图。 - Omar Mahmoud
不完整的信息,我们不能在使用这段代码时花费整个一天。 - Ramkesh Yadav

0

尝试在XML中将以下属性应用于NavigationView,而不是新样式。

    app:itemTextAppearance="@style/MyCustomNavStyle"

打开style.xml文件,在其中添加新的样式:
 <style name="MyCustomNavStyle"> <item 
 name="android:fontFamily">@font/montserrat_regular</item> </style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接