SearchView Focus And Show Keyboard On Expand (Iconified = false)

May 22, 2018

Add android.widget.SearchView to menu xml (e.g. menu_main.xml).

<menu xmlns:android=""

    <item android:id="@+id/action_search"
        app:actionViewClass="android.widget.SearchView" />

        app:showAsAction="never" />

Activity code.

fun View.showKeyboard() {    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)}fun View.hideKeyboard() {    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager    imm.hideSoftInputFromWindow(getWindowToken(), 0)}class MainActivity : AppCompatActivity() {    override fun onCreateOptionsMenu(menu: Menu): Boolean {        menuInflater.inflate(, menu)        val searchItem =  menu.findItem(        val searchView = searchItem.actionView as SearchView        searchView.setOnQueryTextFocusChangeListener { view, hasFocus ->            if (hasFocus) {                searchView.showKeyboard()            }            else {                searchView.hideKeyboard()            }        }        searchItem.setOnActionExpandListener(object: MenuItem.OnActionExpandListener {            override fun onMenuItemActionExpand(p0: MenuItem?): Boolean {                searchView.isIconified = false                searchView.requestFocusFromTouch()                return true            }            override fun onMenuItemActionCollapse(p0: MenuItem?): Boolean {                // when back, clear all search                searchView.setQuery("", true)                return true            }        })        searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener {            override fun onQueryTextSubmit(query: String?): Boolean {                return true            }            override fun onQueryTextChange(newText: String): Boolean {                // do something on search text changed                return true            }        })    }}  

❤️ 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.