how to change android SearchView text

前端 未结 5 2242

Is there a setText() method for SearchView or something like that? I try to set the search text in the searchView like this but there is no method for like this.

<         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 02:05

    If you want pre-fil your SearchView with some text searchView.setQuery(text, false) would not work out of the box. the reason is when SearchView gets expanded

    searchView.onActionViewExpanded()

    get called which calls searchView.setText("") and clears any text we have set.

    Solution is to set an Expand listener and set the pre-fil text once the SearchView is expanded

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        val searchView = menu.findItem(R.id.action_search).actionView as SearchView
        menu.findItem(R.id.action_search).setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
            override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
                // it is important to call this before we set our own query text.
                searchView.onActionViewExpanded()
                searchView.setQuery("Prefil Text", false)
                return true
            }
    
            override fun onMenuItemActionCollapse(item: MenuItem?) = true
        })
        return true
    }
    

提交回复
热议问题