87.android 简单的SearchView搜索框,以及去除黑框
//第一步 我的Activity布局,一个SearchView,一个ListView:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <SearchView android:queryHint="搜索" android:iconifiedByDefault="false" android:background="@color/f2eeee" android:id="@+id/mSearchView" android:layout_width="match_parent" android:layout_height="wrap_content" /> <!-- 为SearchView定义自动补齐的ListView--> <ListView android:id="@+id/mListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
//第二步 在Activity里使用:
// 数据的列表 private final String[] mStrings = { "张三", "李四", "王五", "赵六" };
//适配器
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, mStrings); mListView.setAdapter(adapter); //设置lv可以被过虑 mListView.setTextFilterEnabled(true); // 设置该SearchView默认是否自动缩小为图标 // mSearchView.setIconifiedByDefault(false); // 为该SearchView组件设置事件监听器 mSearchView.setOnQueryTextListener(this); // 设置该SearchView显示搜索按钮 // mSearchView.setSubmitButtonEnabled(true);
//两个重要方法+去除黑框:
// 用户输入字符时激发该方法 @Override public boolean onQueryTextChange(String newText) { Toast.makeText(getContext(), "textChange--->" + newText, Toast.LENGTH_SHORT).show(); if (TextUtils.isEmpty(newText)) { // 清除ListView的过滤 mListView.clearTextFilter(); } else { // 使用用户输入的内容对ListView的列表项进行过滤 mListView.setFilterText(newText); //隐藏弹出的黑框 mListView.dispatchDisplayHint(View.INVISIBLE); } return true; } // 单击搜索按钮时激发该方法 @Override public boolean onQueryTextSubmit(String query) { // 实际应用中应该在该方法内执行实际查询 // 此处仅使用Toast显示用户输入的查询内容 //输入完成后,点击搜索按钮或者软键盘的搜索按钮,就会触发这个 Toast.makeText(getContext(), "您的选择是:" + query, Toast.LENGTH_SHORT).show(); return false; }
//---------------------------------------------------------------------完------------------------------------------------------------------------