Android Material Design 中其实有搜索框SearchView,但是并不怎么好用,所以这里介绍三方的一个控件
MaterialSearchView,地址:https://github.com/MiguelCatalan/MaterialSearchView
1.依赖
implementation 'com.miguelcatalan:materialsearchview:1.4.0'
2.布局
<!— Must be last for right layering display —>
<FrameLayout
android:id="@+id/toolbar_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/theme_primary" />
<com.miguelcatalan.materialsearchview.MaterialSearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
3.添加menu
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_action_search"
android:orderInCategory="100"
android:title="@string/abc_search_hint"
app:showAsAction="always" />
4.添加选项菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return super.onCreateOptionsMenu(menu);;
}
5.监听
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//Do some magic
//点击搜索按钮提交搜索的内容
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
//Do some magic
//搜索框中内容发生改变
return false;
}
});
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
//Do some magic
//搜索框展开
}
@Override
public void onSearchViewClosed() {
//Do some magic
//搜索框折叠
}
});