Isabelle
Isabelle

Reputation: 1517

Android - SearchView - setTypeface not available

For some reason, I'm not able to setTypeface on a SearchView. Here is my code to try to change the font:

searchView = findViewById(R.id.searchview_invite_friends_search_contact);
Typeface myFont = Typeface.createFromAsset(getAssets(),"fonts/myFont.ttf");
searchView.setTypeface(myFont);

I defined it like this in a the xml:

<SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="@string/searchview_invite_friends_search_contact"
        android:iconifiedByDefault="false"
        android:layout_centerHorizontal="true"
        android:background="@android:color/white"
        android:searchIcon="@drawable/icon_search"
        android:focusable="false"
        android:layout_height="45dp"
        android:queryBackground="@color/transparent"
        android:gravity="center_horizontal"
        >

Upvotes: 2

Views: 2323

Answers (3)

Kong Far
Kong Far

Reputation: 191

A possibility via xml (not tested across OS versions and devices):

Create a resource that is identical with @layout/abc_search_view. Lets name it "search_field.xml"

Inside the search_field.xml set the fontfamiliy on the "<view class="androidx.appcompat.widget.SearchView$SearchAutoComplete>" element.

...
<view class="androidx.appcompat.widget.SearchView$SearchAutoComplete"
              android:id="@+id/search_src_text"
              ...
              app:fontFamily="@font/[YOUR_FONT_RESOURCE]
              />
...

Create a resource style... lets name it my_search_view_style

<style name="my_search_view_style" parent="Widget.AppCompat.SearchView">
   <item name="layout">@layout/search_field</item>
</style>here

Finaly set the my_search_view_style style on the SearchView

<androidx.appcompat.widget.SearchView
    android:id="@+id/searchView"
    style="@style/my_search_view_style"
    ...
/>

Upvotes: 0

chhengheng
chhengheng

Reputation: 11

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

Upvotes: 1

Slamper
Slamper

Reputation: 445

The SearchView contains a TextView which you first have to find to change its Typeface like this.

 TextView searchText = (TextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
 searchText.setTypeface(<your Typeface>);

This is for the SearchView in the v7 Android Support library.

For the normal SearchView in the android.widget package see https://stackoverflow.com/a/30915643/3233251

Upvotes: 3

Related Questions