GitHub源码地址:https://github.com/zlw1347822194/SearcohViews
1,导入一下design的依赖
2,布局文件很简单,只有两个控件
注意:android:iconifiedByDefault 里面最好为 false
让搜索框默认就展开设置setIconifiedByDefault(false)即可
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="zlw.com.searcohview.MainActivity">
<SearchView
android:id="@+id/main_searchview"
android:queryHint="请输入搜索内容"
android:iconifiedByDefault="false"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</SearchView>
<ListView
android:id="@+id/main_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
3,代码部分
package zlw.com.searcohview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
public class MainActivity extends AppCompatActivity {
private String[] searcoh = {"hhhhh","cccccc","wwwwww","ddddd","aaaaa"};
private SearchView main_searchview;
private ListView main_listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
}
private void findViews() {
main_searchview = (SearchView) findViewById(R.id.main_searchview);
main_listview = (ListView) findViewById(R.id.main_listview);
main_listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, searcoh));
main_listview.setTextFilterEnabled(true);
main_searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() // 设置搜索文本监听{
@Override
public boolean onQueryTextSubmit(String query) {//搜索时触发事件
return false;
}
@Override
public boolean onQueryTextChange(String newText) {//搜索时根据文本框动态改变搜索内容
if (!TextUtils.isEmpty(newText)){
main_listview.setFilterText(newText);
} else {
main_listview.clearChoices();
}
return false;
}
});
}
}
4,实例:如下!
只供学习和参考,有什么不足请大牛指点,谢谢。