Android Expand SearchView Without Focus (Hide Keyboard)

Apr 28, 2019

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 into SearchView.
  • To prevent focus, call searchView.clearFocus on searchView.doOnLayout (using android-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>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.