我想将Android的DrawerLayout
和NavigationView
用于菜单,但我不知道如何让菜单项使用自定义字体。有没有人成功实施?
答案 0 :(得分:4)
使用此方法传递抽屉中的基本视图
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) {
}
}
答案 1 :(得分:4)
Omar Mahmoud answer将会奏效。但它并没有使用字体缓存,这意味着你不断地从磁盘读取,这很慢。显然旧设备可能会泄漏内存 - 尽管我还没有证实这一点。至少,效率非常低。
如果你想要的只是字体缓存,请按照步骤1-3进行操作。这是必须的。但是,让我们超越:让我们实施一个使用Android Data Binding库(信用卡Lisa Wray)的解决方案,以便您可以在自己的库中添加自定义字体具有一个行的布局。哦,我是否提到你不必延长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上找到它here。如果她关闭项目,我将包含此实施所需的部分。您需要添加另一个类才能在布局中使用数据绑定,但我将在第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
}
}
答案 2 :(得分:1)
步骤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"
对于任何可能会在这里寻求简单解决方案的人