在Android中的SearchView自定义字体

And*_*ech 12 fonts android searchview android-typeface

我一直在尝试将自定义字体设置为android.support.v7.widget.SearchView查询提示和View.I中输入的文本.我尝试通过创建TypeFace对象动态地将字体从assests设置为searchView,但问题是"SearchView不包含一个setTypeface(Typeface tf)方法." 我确实尝试过自定义的SearchView类但找不到.

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

    }
Run Code Online (Sandbox Code Playgroud)

irv*_*ngh 42

这里的解决方法是首先获取searchView的textView,然后更改textView的字体:

 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);
Run Code Online (Sandbox Code Playgroud)

或者,如果您不使用appcompatv7:

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

然后像往常一样设置字体.

  • 对于androidX,要搜索的ID为androidx.appcompat.R.id.search_src_text (5认同)
  • 虽然我认为这是有效的,但您假设SearchView类的实现细节.这些可能随时改变,这不是一个安全的假设. (3认同)
  • @amitav13 如果我使用 `androidx.appcompat.R.id.search_src_text` 作为 ID,我会在 AndroidX 中得到一个空的 `TextView`。但是,使用 `getIdentifier()` 的第二种方法完全按照建议的方式对我有用。我不必将 `android:id/search_src_text` 更改为 `androidx.appcompat.R.id.search_src_text`。任何想法为什么`androidx.appcompat.R.id.search_src_text` 不起作用? (3认同)

小智 5

要从 xml 字体文件夹以编程方式更改 searchview 中的字体系列:

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);
Run Code Online (Sandbox Code Playgroud)