0

I have an activity only for the SearchView which is focused on created so the soft keyboard pops up.

This is the code (kotlin):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_search_input)

    searchInput.isIconified = false

    searchInputLayout.setOnClickListener {
        finish()
    }
}


override fun onBackPressed() {
    searchInput.clearFocus()
    finish()
}

As you can see I try to close the activity when back button is pressed but it only closes the soft keyboard.

How can I do this??

Thanks in advance

qtmfld
  • 2,916
  • 2
  • 21
  • 36
  • 3
    Does this answer your question? [Intercept back button from soft keyboard](https://stackoverflow.com/questions/3940127/intercept-back-button-from-soft-keyboard) – qtmfld Feb 24 '20 at 03:27

3 Answers3

1

You can create customized view and implement onKeyPreIme(keyCode: Int, event: KeyEvent) and check for keyCode == KeyEvent.KEYCODE_BACK event.

Hope this answer will explain it to you furthermore.

Edited:

try to implement these for your SearchView:

searchInput.setOnQueryTextFocusChangeListener{ _, b->
    if(!b){
     searchview.isIconified = true
     finish()
   }
}
0

I would recommend you try using InputMethodManager to hide the keyboard and then close your activity. For example adding a kotlin extension as below

fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

And then in your activity backpress method you invoke the hideKeyboard method

override fun onBackPressed() {
 searchInput.hideKeyboard()
 finish() 
}
0

Use this static method to close keyboard

//to hide keyboard
public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    assert imm != null;
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

this method is in JAVA

Hope this will help!

Rahul Gaur
  • 1,661
  • 1
  • 13
  • 29