在安卓系统中如何自定义SearchView的字体?

21

我一直在尝试将自定义字体设置到android.support.v7.widget.SearchView的查询提示和视图中输入的文本。我尝试从资源中动态设置字体到searchView,创建一个TypeFace对象,但问题在于"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..

    }

尝试使用以下代码:searchView.setQueryHint(Html.fromHtml("<font face = tf>" + getResources().getString(R.string.search_hint) + "</font>")); - Apurva
@Apurva 让我检查一下,然后告诉你。 - AndroidMech
@Apurva 不行,这个不起作用。 - AndroidMech
5个回答

55

解决方法是先获取searchView的textView,然后为textView更改字体类型:

思路:获取searchView中的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);

或者,如果您没有使用appcompatv7:

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

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


4
虽然我认为这个方法可行,但你假设了SearchView类的实现细节。这些细节随时可能发生变化,这是一个不安全的假设。 - Gabe Sechan
6
对于androidX,需要搜索的ID是androidx.appcompat.R.id.search_src_text。 - amitavk
3
如果在AndroidX中我使用androidx.appcompat.R.id.search_src_text作为ID,我会得到一个空的TextView。然而,使用getIdentifier()的第二种方法对我来说完全按照建议的方式起作用。我不需要将android:id/search_src_text更改为androidx.appcompat.R.id.search_src_text。有任何想法为什么androidx.appcompat.R.id.search_src_text无法工作? - Shahood ul Hassan

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);

4

针对 Kotlin 和 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

1

感谢之前的回答,我找到了我认为最好的解决方案,希望您也能觉得这是最简洁的答案。

这适用于 android.widget 包内的 SearchView 类。

首先,创建一个如下所示的扩展:

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
}

然后在任何您喜欢的位置使用这个扩展程序:

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

你可能想从资产或其他方式获取字体,但其余部分相同。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接