Search code examples
androidfontssearchviewandroid-typeface

SearchView custom font in android


I have been trying to set custom font to the android.support.v7.widget.SearchView query hint and the text entered in the View.I did try setting the font dynamically from the assests to the searchView by creating a TypeFace object, but the problem occurs that "SearchView doesn't contain a setTypeface(Typeface tf) method." I did try for a custom SearchView class but couldn't find one.

 private void setFont(String font1, String font2, String font3)
 {
        Typeface tf = null;

        tf = UiUtil.changeFont(MainActivity.this, font1);
        btn1.setTypeface(tf);

        tf = UiUtil.changeFont(MainActivity.this, font2);
        btn2.setTypeface(tf);

        tf = UiUtil.changeFont(MainActivity.this, font3);
        btn3.setTypeface(tf);

         tf = UiUtil.changeFont(MainActivity.this, font3);
        // no set typeface method..

    }

Solution

  • 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.