1.添加依赖
implementation 'com.miguelcatalan:materialsearchview:1.4.0'
2.布局
<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="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:titleTextColor="@color/white"></android.support.v7.widget.Toolbar>
<com.miguelcatalan.materialsearchview.MaterialSearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
3.创建选项菜单以及解绑
@Override
public void onBackPressed() {
if (mSearchView.isSearchOpen()) {
mSearchView.closeSearch();
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.item, menu);
mSearchViewItem = menu.findItem(R.id.action_search);
//隐藏menu,搜索框就不见了,想要搜索框不见只能使用mSearchViewItem
mSearchViewItem.setVisible(false);
mSearchView.setMenuItem(mSearchViewItem);
return super.onCreateOptionsMenu(menu);
}
4.获取控件结束后监听事件
MaterialSearchView mSearchView = (MaterialSearchView) findViewById(R.id.search_view);
mSearchView.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;
}
});
mSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
//Do some magic
//搜索框展开
}
@Override
public void onSearchViewClosed() {
//Do some magic
//搜索框折叠
}
});
网友评论