Android Studio 2.3.3、Android 4.3。
在我的 fragment 中,我有 searchView 组件(不在工具栏中)。这是我的 fragment 。
fragment 布局.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginStart="20dp"
android:background="@drawable/search_view_bg"
app:defaultQueryHint="@string/settings"
app:searchHintIcon="@null" />
</LinearLayout>
在我的 fragment 中:
private void init(View view) {
searchView = view.findViewById(R.id.searchView);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setSuggestionsAdapter(new SearchCatalogSuggestionsAdapter(getActivity()));
ViewCompat.setLayoutDirection(view.findViewById(R.id.searchView), ViewCompat.LAYOUT_DIRECTION_RTL);
}
searchView 获得焦点时的结果:
如您所见,仅当 searchView 处于焦点时才会显示提示。 但我还需要在 searchView 未处于焦点时显示提示。我希望提示始终可见。
附言如果使用方法 searchView.setIconified(false)
然后 searchView 自动获得焦点。但我只需要在用户点击 searchView 时获得焦点。
最佳答案
我找到了适用于 Android 4.3+ 的解决方案:
我使用麦克风图标,禁用点击它并用自定义图标(玻璃)替换它
300 毫秒后隐藏键盘(因为
onActionViewExpanded()
显示软键盘)
结果我有:
- searchView 未获得焦点时显示提示
- 当 searchView 处于焦点和 searchView 未处于焦点时在右侧显示图标
这是我的代码 fragment :
Java代码:
ImageView voiceButtonIcon = view.findViewById(android.support.v7.appcompat.R.id.search_voice_btn);
voiceButtonIcon.setImageResource(R.drawable.ic_search_black);
voiceButtonIcon.setEnabled(false);
// Workaround! Show hint when searchView has no focus
searchView.onActionViewExpanded();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
searchView.clearFocus();
}
}, 300);
布局 xml:
<android.support.v7.widget.SearchView
android:id="@+id/searchView"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginStart="20dp"
android:background="@drawable/search_view_bg"
android:theme="@style/SearchViewTheme"
app:defaultQueryHint="@string/settings"
app:searchHintIcon="@null" />
结果: searchView 没有焦点:
和 searchView 具有焦点:
所以提示总是显示!
关于安卓 4.3 : Not focus searchView not show hint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46681500/