Show SearchView
as expenaded (not icon, but show EditText) but don't focus (don't show keyboard) on activity startup.
- Use
androidx.appcompat.widget.SearchView
- Call MenuItem.expandActionView to expand
MenuItem
from icon intoSearchView
. - To prevent focus, call
searchView.clearFocus
onsearchView.doOnLayout
(usingandroid-ktx
)
import androidx.core.view.doOnLayoutimport androidx.appcompat.widget.SearchViewclass TestSearchViewActivity : AppCompatActivity() { override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.testsearchview, menu) val searchItem = menu.findItem(R.id.action_search) searchView = searchItem.actionView as SearchView searchItem.expandActionView() searchView.doOnLayout { searchView.clearFocus() } return super.onCreateOptionsMenu(menu) }}
Menu Layout
<?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:title="Search"
android:icon="@drawable/ic_search_black_24dp"
app:iconTint="@android:color/white"
app:showAsAction="collapseActionView|always"
app:actionViewClass="androidx.appcompat.widget.SearchView"
/>
</menu>