1、搜索框外观:
创建menu->menu->sear Item:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/app_bar_search"
android:icon="@drawable/ic_search_black_24dp"
android:title="Search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always"></item>
<item
android:id="@+id/reload"
android:title="重新加载" />
<item
android:id="@+id/item233"
android:title="退出" />
</menu>
?注意这里需要找到showAsAction并选中always
2、活动里写入:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu,menu);
SearchView searchView=(SearchView) menu.findItem(R.id.app_bar_search).getActionView();
searchView.setMaxWidth(500);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
query=query.trim();
lists2=new ArrayList<>();
if(!query.equals("")){
for(int i=0;i<myData2.queryNum();i++){
if(myData2.queryName(i).contains(query) || myData2.queryPassword(i).contains(query)){
ListViewItemBean itemBean=new ListViewItemBean();
itemBean.text1=myData2.queryName(i);
itemBean.text2=myData2.queryPassword(i);
lists2.add(itemBean);
}
}
ListViewAadpter adpter=new ListViewAadpter(MainActivity8son1.this,R.layout.list_view_item,lists2);
listView.setAdapter(adpter);
}
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.app_bar_search:
break;
case R.id.item233:
startActivity(new Intent(MainActivity8son1.this, MainActivity8.class));
break;
case R.id.reload:
ListViewAadpter adpter=new ListViewAadpter(MainActivity8son1.this,R.layout.list_view_item,lists);
listView.setAdapter(adpter);
break;
}
return super.onOptionsItemSelected(item);
}
其中关键搜索部分的代码为:
SearchView searchView=(SearchView) menu.findItem(R.id.app_bar_search).getActionView();//初始化搜索框
searchView.setMaxWidth(500);//设置长度
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {//搜索框监听
@Override
public boolean onQueryTextSubmit(String query) {//回车键监听
query=query.trim();
lists2=new ArrayList<>();
if(!query.equals("")){
for(int i=0;i<myData2.queryNum();i++){
if(myData2.queryName(i).contains(query) || myData2.queryPassword(i).contains(query)){
ListViewItemBean itemBean=new ListViewItemBean();
itemBean.text1=myData2.queryName(i);
itemBean.text2=myData2.queryPassword(i);
lists2.add(itemBean);
}
}
ListViewAadpter adpter=new ListViewAadpter(MainActivity8son1.this,R.layout.list_view_item,lists2);
listView.setAdapter(adpter);
}
return true;//false表示未处理完会往下传递,true表示处理完不会往下传递
}
@Override
public boolean onQueryTextChange(String newText) {//实时监听
return false;
}
});
|