Search code examples
androidtoolbarsearchview

SearchView in Toolbar only in "search mode"


I have MainActivity and SearchAcitivty. When I click "Szukaj" ("Search") I open SearchAcitivty:

MainActivity

When I open SearchActivity, it shows a list with the option of clicking the magnifying glass to search views in list view.

SearchActivity - list

I would like to start activity immediately in "search mode" (as clicked magnifying glass) or, what's more important, don't back to list when the user clicks back button, but to MainActivity (Facebook has this functionality)

Search mode

Thanks in advance for any hints.


Solution

  • I had to add MenuItem.OnActionExpandListener to my MenuItem to finish activity when SearchView is collapsed and call method menuItem.expandActionView() to expand SearchView on start activity:

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.search_menu, menu)
        val menuItem = menu?.findItem(R.id.searchIcon)
        menuItem.setOnActionExpandListener(this)
        menuItem.expandActionView()
        return true
    }
    
    override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
        return true
    }
    
    override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
        finish()
        overridePendingTransition(0, 0)
        return true
    }
    

    Hope it can help you