Tap outside edittext to lose focus

Viewed 48107

I just want when click outside the "edittext" to automatically lose focus and hide keyboard. At the moment, if I click on the "edittext" it focuses but i need to hit the back button to unfocus.

9 Answers

Here universal method for all screens. Put it in your activity

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    clearFocusOnOutsideClick()
    return super.dispatchTouchEvent(ev)
}
/*
* Clear focus on outside click
* */
private fun clearFocusOnOutsideClick() {
    currentFocus?.apply {
        if (this is EditText) {
            clearFocus()
        }
        //Hide keyboard
        val imm: InputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}

I had the same requirement as I had to hide the keyboard once I touch anywhere outside my EditText box. The setOnFocusChangeListener does not do the job as even if you touch outside the edit text box is still selected.

For this I used the solution edc598 here.

  • I first got the MainLayout containing the whole view and add touch listener to it.
  • When onTouch event was triggered I check if the EditText box has focus.
  • If the EditText box has focus then I check the event's X-Y co-ordinates.
  • Based on the placement of my EditText box I hide the key board if touched anywhere outside the box

Code sample modified from here:

LinearLayout MainLayout = (LinearLayout) findViewById(R.id.MainLayout);
EditText textBox        = (EditText) findViewById(R.id.textBox);   
int X_TOP_LEFT      = 157;
int Y_TOP_LEFT      = 388;
int X_BOTTOM_RIGHT  = 473;
int Y_BOTTOM_RIGHT  = 570;   
MainLayout.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        if(textBox.isFocused()){

            Log.i("Focussed", "--" + event.getX() + " : " + event.getY() + "--");

            if(event.getX() <= 157 || event.getY() <= 388 || event.getX() >= 473 || event.getY() >= 569){
                //Will only enter this if the EditText already has focus
                //And if a touch event happens outside of the EditText
                textBox.clearFocus();
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                //Do something else
            }
        }
        Log.i("X-Y coordinate", "--" + event.getX() + " : " + event.getY() + "--");
    //Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
        return false;
    }
});
Related