介绍:
SearchView时搜索组件,可以让用户输入文字,见他输入匹配结果
效果:
基本的用法 我就不详细描述了
这里主要说一些我遇到的问题:
如下:
一、点击listView后 让文字自动补全到searchView上:
首先需要设置adapter 然后这只listView的点击事件:
代码语言:javascript复制private final String[] mStrings = {"我爱Java","安卓无敌","好好学习"};
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mStrings);
listView.setAdapter(adapter);
然后对listView添加 item的监听事件:
代码语言:javascript复制listView.setOnItemClickListener(new ListView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Object string = adapter.getItem(position);
searchView.setQuery(string.toString(),true);
}
});
二、删除listView自带过滤器的黑框:
在 onQueryTextChange
对adapter设置:adapter.getFilter().filter(newText.toString());
代码语言:javascript复制@Override
public boolean onQueryTextChange(String newText) {
//如果newText长度不为0
if (TextUtils.isEmpty(newText)){
listView.clearTextFilter();
}else{
listView.setFilterText(newText);
//adapter.getFilter().filter(newText.toString());//替换成本句后消失黑框!!!
}
return true;
}
下面给出效果图的的完整实现方法:
代码语言:javascript复制public class MainActivity extends Activity {
private SearchView searchView;
private ListView listView;
//定义自动完成的列表
private final String[] mStrings = {"我爱Java","安卓无敌","好好学习"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv);
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mStrings);
listView.setAdapter(adapter);
//为ListView启动过滤
listView.setTextFilterEnabled(true);
searchView = (SearchView) findViewById(R.id.sv);
//设置SearchView自动缩小为图标
searchView.setIconifiedByDefault(false);//设为true则搜索栏 缩小成俄日一个图标点击展开
//设置该SearchView显示搜索按钮
searchView.setSubmitButtonEnabled(true);
//设置默认提示文字
searchView.setQueryHint("输入您想查找的内容");
//配置监听器
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//点击搜索按钮时触发
@Override
public boolean onQueryTextSubmit(String query) {
//此处添加查询开始后的具体时间和方法
Toast.makeText(MainActivity.this,"you choose:" query,Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
//如果newText长度不为0
if (TextUtils.isEmpty(newText)){
listView.clearTextFilter();
}else{
listView.setFilterText(newText);
// adapter.getFilter().filter(newText.toString());//替换成本句后消失黑框!!!
}
return true;
}
});
listView.setOnItemClickListener(new ListView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Object string = adapter.getItem(position);
searchView.setQuery(string.toString(),true);
}
});
}
}
最后给出布局如下:
代码语言:javascript复制