SearchView custom font in android

To change the font family in searchview programmatically from xml font folder:

Typeface tf = ResourcesCompat.getFont(dis,R.font.montserrat_regular);
TextView searchText = (TextView)search_view.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchText.setTypeface(tf);

The workaround here is to first get the searchView's textView and then change the typeface for the textView instead:

 TextView searchText = (TextView)
 searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
 Typeface myCustomFont = Typeface.createFromAsset(getAssets(),"fonts/myFont.ttf");
 searchText.setTypeface(myCustomFont);

Or, if you're not using appcompatv7:

 int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
 TextView searchText = (TextView) searchView.findViewById(id);

then set the typeface as usual.


Thanks to all the previous answers, I found my best solution witch I hope that you find it the cleanest answer, too.

This is working for SearchView class inside the package android.widget

First, create an extension like below:

import android.graphics.Typeface
import android.widget.SearchView
import android.widget.TextView

fun SearchView.setTypeFace(typeface: Typeface?) {
    val id = context.resources.getIdentifier("android:id/search_src_text", null, null)
    val searchText = searchView.findViewById(id) as TextView
    searchText.typeface = typeface
}

Then use this extension wherever you like:

val typeface = ResourcesCompat.getFont(requireContext(), R.font.sans)
searchView.setTypeFace(typeface)

You may want to get typeface from assets or other ways. but the rest is the same.


For Kotlin and Androidx

val face: Typeface = Typeface.createFromAsset(context?.assets, "font.otf")
val searchText = searchView.findViewById<View>(androidx.appcompat.R.id.search_src_text) as TextView
searchText.typeface = face