You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms Android:移除SearchBar聚焦/输入时的文本下划线

关于Xamarin Forms Android SearchBar移除聚焦/输入状态下文本下方线条的问题解答

1. 需求是否可行?

完全可行。Android原生控件的样式均可通过代码或资源文件定制,你要移除的是SearchView内部EditText在聚焦/输入时显示的下划线,属于可修改的样式范畴。

2. 具体实现方式

你已经通过自定义渲染器拿到了SearchView内部的EditText(search_src_text对应的控件),只需要针对这个EditText做样式修改即可,之前的尝试没生效是因为没找对修改的对象:

在你的自定义渲染器中,找到获取EditText的代码段后,添加以下代码:

// 移除EditText的默认背景(包含下划线)
textView.SetBackground(null);

// 针对部分Android版本,额外设置背景色调为透明,确保聚焦时无线条
AndroidX.Core.View.ViewCompat.SetBackgroundTintList(textView, Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Transparent));

完整修改后的关键代码片段:

protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
    base.OnElementChanged(e);

    SearchView searchView = Control;
    searchView.SetInputType(InputTypes.ClassText | InputTypes.TextVariationNormal);

    int textViewId = searchView.Context.Resources.GetIdentifier("android:id/search_src_text", null, null);
    EditText textView = (searchView.FindViewById(textViewId) as EditText);

    // 原有EditText样式设置代码
    textView.SetBackgroundColor(G.Color.ParseColor("#FFFFFF"));
    textView.SetTextColor(G.Color.ParseColor("#191E24"));
    textView.SetHintTextColor(G.Color.ParseColor("#191E24"));
    textView.SetTextSize(Android.Util.ComplexUnitType.Dip, 16);
    textView.SetPadding(8, 0, 40, 0);

    // 添加这两行代码移除下划线
    textView.SetBackground(null);
    AndroidX.Core.View.ViewCompat.SetBackgroundTintList(textView, Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Transparent));

    // 其余原有代码
    int searchIconId = Context.Resources.GetIdentifier("android:id/search_mag_icon", null, null);
    ImageView searchViewIcon = searchView.FindViewById<ImageView>(searchIconId);
    searchViewIcon.SetImageDrawable(null);

    int searchCloseIconId = Context.Resources.GetIdentifier("android:id/search_close_btn", null, null);
    ImageView searchClose = searchView.FindViewById<ImageView>(searchCloseIconId);
    searchClose.SetPadding(8, 0, 8, 0);

    searchView.Iconified = false;
    searchView.SetIconifiedByDefault(false);
}

注意:如果你的项目未使用AndroidX,将AndroidX.Core.View.ViewCompat替换为Android.Support.V4.View.ViewCompat即可。

3. 需要学习的内容

  • Xamarin.Forms自定义渲染器机制:理解如何将Xamarin.Forms抽象控件映射到Android原生控件,掌握OnElementChanged生命周期方法的使用
  • Android原生SearchView结构:熟悉SearchView内部的子控件层级与系统资源ID(如search_src_text、search_plate等)
  • Android EditText样式定制:学习EditText的背景、色调(BackgroundTint)、状态列表(ColorStateList)等样式属性的修改方式
  • Android资源标识符使用:掌握Resources.GetIdentifier的用法,用于获取系统内置控件的ID

内容的提问来源于stack exchange,提问作者Misael Moneró

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:40:38