效果图
实现方式:
首先创建xml布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".SearchFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/searchbar_scrolling_view_behavior">
<!-- 显示屏幕中需要的数据-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.core.widget.NestedScrollView>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.search.SearchBar
android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="搜索" />
</com.google.android.material.appbar.AppBarLayout>
<!-- 点搜索框后显示的view-->
<com.google.android.material.search.SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="搜索view"
app:layout_anchor="@id/search_bar">
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.search.SearchView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
再创建一个菜单menu_search,用来添加到searchView的搜索栏中
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@drawable/baseline_search_24"
android:title="搜索"
app:showAsAction="ifRoom" />
</menu>
fragment/activity代码:
class SearchFragment : Fragment() {
private lateinit var binding: FragmentSearchBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSearchBinding.inflate(layoutInflater)
binding.searchView.inflateMenu(R.menu.menu_search)
binding.searchView.setOnMenuItemClickListener {
when (it.itemId) {
R.id.action_search -> {
binding.result.text = binding.searchView.text
Toast.makeText(requireContext(), "点击", Toast.LENGTH_LONG).show()
}
}
true
}
binding.searchView.editText.setOnEditorActionListener { v, actionId, event ->
binding.searchBar.setText(binding.searchView.text)
binding.searchView.hide()
binding.result.text = binding.searchView.text
false
}
return binding.root
}
}