Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: how to get searchView submit

I have a SearchView:

<SearchView
    android:id="@+id/searchBar"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:visibility="visible"/>

I want to add a custom action when the submit button is pressed.

This is what I have so far:

searchBar.setOnSearchClickListener {
  //do some stuff
}

All the information I found is old and not in kotlin.

How can I get trigger an action when the search icon on the keyboard is tapped?

like image 786
Bozzo Avatar asked Nov 15 '17 09:11

Bozzo


People also ask

How do I get SearchView text?

To get text of SearchView , use searchView. getQuery() .

What is onQueryTextSubmit?

onQueryTextSubmit. Added in API level 11. public abstract boolean onQueryTextSubmit (String query) Called when the user submits the query. This could be due to a key press on the keyboard or due to pressing a submit button.


1 Answers

Try doing this:

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.main, menu)

    val searchItem = menu.findItem(R.id.search_city)
    searchView = searchItem.actionView as SearchView
    searchView.setQueryHint("Search View Hint")

    searchView.setOnQueryTextListener(object : OnQueryTextListener {

        override fun onQueryTextChange(newText: String): Boolean {
            return false
        }

        override fun onQueryTextSubmit(query: String): Boolean {
            // task HERE
            return false
        }

    })

    return true
}

Response link: Listen to keyboard event

like image 178
Maurice Avatar answered Oct 09 '22 20:10

Maurice