Insert text into SearchView query at current cursor position

Viewed 81

I was able to add a character at the end of the SearchView query string currently in the text field:

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.list_fragment_menu, menu)

    val search = menu.findItem(R.id.menu_search)
    val searchView = search.actionView as? SearchView
    searchView?.isSubmitButtonEnabled = true
    searchView?.setOnQueryTextListener(this)
    binding.button1.setOnClickListener {searchView?.setQuery(searchView.query.toString() + "Ɣ",false)}
}

But how can I insert the character into query string at the current cursor position? In other words, how do I retrieve the current cursor position? Thank you!

1 Answers

Yes you can do it through the EditText and the Editable to Get the EditText use this:

val editText = searchView.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)

And to get the Cursor position use :

editText.selectionStart

And to Insert a text on the Cursor position you can use it like below :

 val editText = searchView.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)
 

 btn_click_me.setOnClickListener {
       val editable = editText.text
       editable.insert(editText.selectionStart, "Test")// here to insert a text at the cursor position
     }
Related