2

I'm facing the following problem:

I'm using a custom font for all my TextViews, Buttons, EditTexts etc.

Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontName);
setTypeface(myTypeface);

The only View which hasn't the custom font is the SearchView Widget (android.support.v7.widget.SearchView), which is added to the menu via xml.

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:id="@+id/menu_item_message_search"
          android:title="@string/search_placeholder"
          android:icon="@android:drawable/ic_menu_search"
          app:showAsAction="ifRoom|collapseActionView"
          app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

Any idea how to set a custom font to this view?

Thank you :)

Jonas
  • 1,432
  • 3
  • 20
  • 27

2 Answers2

2

First you need to find view,

SearchView sv = (SearchView) menu.findItem(R.id. menu_item_message_search);

In this code, I m not sure that it will cast to SearchView although findItem work. Because I added menu not with xml.

After that you can find SearchAutoComplete from SearchView by this code

SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) sv.findViewById(android.support.v7.appcompat.R.id.search_src_text);

And then, you can set Typeface for searchAutoComplete.

searchAutoComplete.setTypeface(typeface)

good luck, I hope this will help you.

Hein Htet Aung
  • 844
  • 4
  • 16
2

I'm using appcompat 22.1.0. Looking at source code of android.support.v7.widget.SearchView class, the text field is a static nested class SearchAutoComplete, which relies on autoCompleteTextViewStyle. Overriding this in your theme will allow you to change font family.

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
    ...
    <item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextView</item>
</style>

<style name="AutoCompleteTextView" parent="Widget.AppCompat.Light.AutoCompleteTextView">
    ...
    <item name="android:textAppearance">@style/AutoCompleteTextViewTextAppearance</item>
</style>

<style name="AutoCompleteTextViewTextAppearance" parent="TextAppearance.AppCompat.Medium.Inverse">
    <item name="android:fontFamily">sans-serif-thin</item>
</style>

Note that android:fontFamily is only available from API 16.

hidro
  • 12,333
  • 6
  • 53
  • 53