如何从 SearchView 中移除焦点?

新手上路,请多包涵

我想从 SearchView 中删除焦点和文本 onResume()

我尝试了 searchView.clearFocus() 但它不起作用。

这是我的 xml 代码:

 <SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/toolbar"
    android:layout_alignTop="@+id/toolbar"
    android:layout_centerVertical="true"
    android:layout_marginBottom="4dp"
    android:layout_marginTop="4dp"
    android:iconifiedByDefault="false"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" />

原文由 Pradeep Deshmukh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 865
2 个回答

我想从 SearchView 中删除焦点和文本 onResume()

要实现这一点,您可以使用 android:focusableInTouchMode 属性将根布局设置为可聚焦,并请求聚焦于 ViewonResume() 中。

例如:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:focusableInTouchMode="true">

    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:iconifiedByDefault="false"/>

</LinearLayout>

然后在你的 Activity

 private View rootView;
private SearchView searchView;

// ...

@Override
protected void onCreate(Bundle savedInstanceState) {

    // ...

    rootView = findViewById(R.id.root_layout);
    searchView = (SearchView) findViewById(R.id.search_view);
}

@Override
protected void onResume() {
    super.onResume();

    searchView.setQuery("", false);
    rootView.requestFocus();
}

原文由 earthw0rmjim 发布,翻译遵循 CC BY-SA 4.0 许可协议

在活动中转到父布局时,在 fragment 中也在 framelayout 中做同样的事情。只需添加此属性:

 android:focusableInTouchMode="true"

原文由 mohd khalid Siddiqui 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题