search menu android code example
Example 1: how to create search function in android studio
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
android:title="@string/search_title"
android:icon="@drawable/ic_search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
Example 2: search bar android studio kotlin
override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.search_menu, menu) val searchItem: MenuItem = menu.findItem(R.id.action_search) if (searchItem != null) { searchView = MenuItemCompat.getActionView(searchItem) as SearchView searchView.setOnCloseListener(object : SearchView.OnCloseListener { override fun onClose(): Boolean { return true } }) val searchPlate = searchView.findViewById(androidx.appcompat.R.id.search_src_text) as EditText searchPlate.hint = "Search" val searchPlateView: View = searchView.findViewById(androidx.appcompat.R.id.search_plate) searchPlateView.setBackgroundColor( ContextCompat.getColor( this, android.R.color.transparent ) ) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean {// do your logic here Toast.makeText(applicationContext, query, Toast.LENGTH_SHORT).show() return false } override fun onQueryTextChange(newText: String?): Boolean { return false } }) val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName)) } return super.onCreateOptionsMenu(menu)}onQueryTextSubmit