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="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.luasoftware.luapass.MainActivity">

    <item android:id="@+id/action_search"
        android:title="Search"
        android:icon="@drawable/ic_search_white_24dp"
        app:showAsAction="collapseActionView|always"
        app:actionViewClass="android.widget.SearchView" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    
</menu>

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(R.menu.menu_main, menu)        val searchItem =  menu.findItem(R.id.action_search)        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.