android – 如何更改导航抽屉字体?
作者:互联网
我想在android中使用我自己的字体导航抽屉.我根据这个答案使用android自带的工作室:https://stackoverflow.com/a/23632492/4393226.
但我不知道如何更改字体并使其成为RTL.
我搜索了很多,我发现了如何制作抽屉RTL.我用这个代码:
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
和
Android – Is Navigation Drawer from right hand side possible?
但正如您所知,这仅适用于API 17及更高版本.
请帮忙!如何更改菜单字体?如何以正确的方式进行布局RTL?!
编辑:
我的字体“TTF”文件是资产/字体,我知道如何使用java为textview设置它,但我不知道如何将其设置为导航抽屉菜单.
解决方法:
我找到了答案:
首先在项目中创建此类:
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;
public class CustomTypefaceSpan extends TypefaceSpan {
private final Typeface newType;
public CustomTypefaceSpan(String family, Typeface type) {
super(family);
newType = type;
}
@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, newType);
}
@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}
int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(tf);
}
}
然后将此方法添加到您想要更改导航抽屉菜单字体的活动中:
private void applyFontToMenuItem(MenuItem mi) {
Typeface font = Typeface.createFromAsset(getAssets(), "ds_digi_b.TTF");
SpannableString mNewTitle = new SpannableString(mi.getTitle());
mNewTitle.setSpan(new CustomTypefaceSpan("" , font), 0 , mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mi.setTitle(mNewTitle);
}
然后添加调用您刚刚在活动中添加的方法:
navView = (NavigationView) findViewById(R.id.navView);
Menu m = navView.getMenu();
for (int i=0;i<m.size();i++) {
MenuItem mi = m.getItem(i);
//for aapplying a font to subMenu ...
SubMenu subMenu = mi.getSubMenu();
if (subMenu!=null && subMenu.size() >0 ) {
for (int j=0; j <subMenu.size();j++) {
MenuItem subMenuItem = subMenu.getItem(j);
applyFontToMenuItem(subMenuItem);
}
}
//the method we have create in activity
applyFontToMenuItem(mi);
}
标签:android,fonts,navigation-drawer,right-to-left 来源: https://codeday.me/bug/20191004/1852727.html