如何在Android中的菜单项上添加自定义字体?

时间:2018-06-04 12:04:13

标签: java android xml

我一直试图在我的菜单项中添加一个字体,并尝试了一些我找到的解决方案,但没有一个能为我工作。

方法1:How to set custom typeface to items in NavigationView?

方法2:

菜单XML

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_notification1"
        android:icon="@mipmap/filter_button"
        android:title="action_notification"
        app:showAsAction="always">
        <menu>
            <item
                android:id="@+id/navmenu_cat"
                android:icon="@mipmap/categories"
                android:orderInCategory="100"
                android:title="@string/categories" />
            <item
                android:id="@+id/navmenu_date"
                android:icon="@mipmap/calendar"
                android:orderInCategory="100"
                android:title="@string/date" />
        </menu>
    </item>
</menu>

MyClass的

public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.work_history, menu);
        for (int i = 0; i < menu.size(); i++) {
            Typeface face = Typeface.createFromAsset(getAssets(), "ar_regular.ttf");
            SpannableStringBuilder title = new SpannableStringBuilder(menu.getItem(i).getTitle().toString());
            title.setSpan(face, 0, title.length(), 0);
            MenuItem menuItem = menu.getItem(i);
            menuItem.setTitle(title);
        }
        return true;
    }

2 个答案:

答案 0 :(得分:0)

你可以使用这个lib https://github.com/chrisjenx/Calligraphy。当您将menuItem附加到上下文时,它会将默认字体设置为

答案 1 :(得分:0)

There is a library https://github.com/chrisjenx/Calligraphy,

Add this dependency to your build gradle

dependencies {
    compile 'uk.co.chrisjenx:calligraphy:2.3.0'
}

Then in your activity override this method

@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
            );
    //....
}

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}