how to change android SearchView text

丶灬走出姿态 提交于 2019-11-28 18:04:41

After wondering and trying I found out that there is a method in the API named setQuery() which you set the searchView text and you may choose to submit the search or not using the boolean parameter.

searchView.setQuery(searchToken, false);

You can use setQuery() to change the text in the textbox.

However, setQuery() method triggers the focus state of a search view, so a keyboard will show on the screen after this method has been invoked.

To fix this problem, just call searchView.clearFocus() after setQuery() method to unfocus it and the keyboard will not show on the screen.

Example:

String suggestWord = intent.getDataString();
searchView.setQuery(suggestWord, false);
searchView.clearFocus();

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
}

this is what worked for me

    MenuItem sItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) sItem.getActionView();

    sItem.expandActionView();
    searchView.setQuery("your text", false);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!