我想使用Android的DrawerLayout
和NavigationView
来创建菜单,但是我不知道如何让菜单项使用自定义字体。是否有人有成功的实现方法?
我想使用Android的DrawerLayout
和NavigationView
来创建菜单,但是我不知道如何让菜单项使用自定义字体。是否有人有成功的实现方法?
TextView
*或任何其他Android类。这需要一些额外的工作,但从长远来看,它会使您的生活变得非常轻松。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.
}
}
}
这个步骤并不复杂。它基本上提取了 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
的实例,但如果您想对此进行单元测试,那么我们需要传递。我们都会写单元测试,对吧?我不会。因此,如果有人想纠正我并提供更可测试的实现,请随时提出!
如果这个库被打包起来,我们就可以直接在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
之前将自定义字体添加到缓存中。此外,setContentView
被DataBindingUtil.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
}
}
步骤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"
如果有人在这里寻找简单的解决方案
在你的抽屉中使用这种方法传递基本视图
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) {
}
}
尝试在XML中将以下属性应用于NavigationView,而不是新样式。
app:itemTextAppearance="@style/MyCustomNavStyle"
<style name="MyCustomNavStyle"> <item
name="android:fontFamily">@font/montserrat_regular</item> </style>