How do I open the SearchView programmatically?

后端 未结 8 1609
既然无缘
既然无缘 2020-12-02 09:19

There is this widget for the ActionBar which called \'SearchView\'. When it\'s not in use, it looks like this:

\

相关标签:
8条回答
  • 2020-12-02 09:22

    I was searching for a solution to expand SearchView programmatically because I need to restore expand state. No one solution was worked for me. Except using Handler().post(). I know it's not a good practice to use post(). But I'm working on legacy project and this workaround is acceptable for me.

    Initialize variables block

    val searchMenuItem = menu.findItem(R.id.menu_search_item)
    val searchView = searchMenuItem.actionView as SearchView
    

    How to expand SearchView:

    Handler().post {
       searchMenuItem.expandActionView()
    }
    

    Reason why post() helps: if your app is not well written it may doing too much work on UI thread. post() ensures that your block of code will be executed when UI thread will be available for execution. Which means if you are using this workaround you can notice small delay between SearchView expanding

    0 讨论(0)
  • 2020-12-02 09:26

    For androidx.appcompat.widget.SearchView,

    searchView.setIconifiedByDefault(true)   // didn't work
    
    searchMenuItem.expandActionView()  // didn't work
    
    MenuItemCompat.expandActionView(searchMenuItem) // didn't work
    
    searchView.onActionViewExpanded()  // didn't work
    

    The following worked for me,

    searchView.findViewById<View>(R.id.search_button).performClick()
    
    0 讨论(0)
  • 2020-12-02 09:29

    To open up a searchView keeping the close_button in the end use this in onCreate:-

    searchView.findViewById(R.id.search_button).performClick();
    
    0 讨论(0)
  • 2020-12-02 09:33

    Try to call expandActionView() on MenuItem, not onActionViewExpanded() on ActionView.

    It works for me.

    MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
    searchView = (SearchView) searchMenuItem.getActionView();
    searchMenuItem.expandActionView();
    
    0 讨论(0)
  • 2020-12-02 09:33

    I know this is late but

    Try calling expandActionView() to open it and collapseActionView() to close it. You can call requestFocus() on the actual Action View via getActionView() to give the search view focus :)

    0 讨论(0)
  • 2020-12-02 09:35

    Expanding the answer of Matthias Robberts:

    I wanted a list fragment to keep it's search value and set it after user returns from other fragment.

    if (myViewModel.filterTextSaved.isNotEmpty()) { // Kotlin, storing state in ViewModel
        searchItem.expandActionView() // needs to come first, otherwise empty text
        theTextArea.setText(courseViewModel.filterTextOnClick)
    }
    

    and for the menu I keep always|collapseActionView, otherwise it stays open when user deletes the text.

    0 讨论(0)
提交回复
热议问题