简体   繁体   中英

How do i add custom font on menu item in Android?

I have been trying to add a font to my menu items and have tried few solutions i found but none of them worked for me.

Method 1 : How to set custom typeface to items in NavigationView?

Method 2:

Menu 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;
    }

you can use this lib https://github.com/chrisjenx/Calligraphy . It will set the default font to your menuItem when you attach it to a context

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM