Tap outside edittext to lose focus

AndroidFocusAndroid Edittext

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

To solve this problem what you have to do is first use setOnFocusChangeListener of that Edittext

edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    Log.d("focus", "focus lost");
                    // Do whatever you want here
                } else {
                    Log.d("focus", "focused");
                }
            }
        });

and then what you need to do is override dispatchTouchEvent in the activity which contains that Edittext see below code

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if ( v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                    Log.d("focus", "touchevent");
                    v.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

Now what will happen is when a user click outside then, firstly this dispatchTouchEvent will get called which then will clear focus from the editext, now your OnFocusChangeListener will get called that focus has been changed, now here you can do anything which you wanted to do, hope it works :)

Solution 2 - Android

@woodshy has the answer for hiding the keyboard, but maybe putting the code in onClick is not as good as putting it in onFocusChanged. As for forcing it to lose focus, you need to set the object you want to transfer the focus to, in its XML file:

android:focusable="true"
android:focusableInTouchMode ="true"

Solution 3 - Android

Suppose your EditText is placed on Linear layout or other ViewGroup. Then you should make this container clickable, focusable and focusableInTouchMode. After that set onClickListener to this container with following code in onClick Override method:

@Override
public void onClick(View view) {
    InputMethodManager imm = (InputMethodManager) view.getContext()
			.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

Solution 4 - Android

You can achieve this by doing the following steps:

1.Make the parent view(content view of your activity) clickable and focusable by adding the following attributes

    android:clickable="true" 
    android:focusableInTouchMode="true" 

2.Implement a hideKeyboard() method

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

3.Lastly, set the onFocusChangeListener of your edittext.

    edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });

Solution 5 - Android

The following code works perfectly for me, and I regularly use this for closing the SoftKeyboard onTouch anywhere outside the EditText.

public void hideSoftKeyboard()
{
        //Hides the SoftKeyboard
        InputMethodManager inputMethodManager = (InputMethodManager)  getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
    
public void setupUI(View view) 
{
        String s = "inside";
        //Set up touch listener for non-text box views to hide keyboard.
        if (!(view instanceof EditText)) {

            view.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard();
                    return false;
                }

            });        
	    }

        
	//If a layout container, iterate over children and seed recursion.
        if (view instanceof ViewGroup) {

            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

                View innerView = ((ViewGroup) view).getChildAt(i);

                setupUI(innerView);
            }
        }    
}

So you just need to call the setupUI() function once in your onCreate() method and voilla, your hidingSoftKeyboard is setup!

For Losing complete focus of the EditText, simply do editText.clearFocus() in your hideSoftKeyboard() function.

Solution 6 - Android

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)
    }
}

[tag:kotlin] [tag:clearfocus] [tag:android] [tag:outside]

Solution 7 - Android

So I searched around a little bit, and no other solutions was exactly what I was looking for. In my opinion the focus behave strangely on EditText views.

What I did was...

  1. Make sure the root view is a RelativeLayout

  2. Add an overlay layout that is OVER the area that will make the keyboard disapear, but not the EditText. Something like below:

In my case, the EditText was in a container at the bottom of the screen. so it covered everyhting else.

  1. Have a method that looks a bit like this one :

    private void hideKeyboard() {
    final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    keyboardOverlay.setVisibility(View.GONE);
    editText.clearFocus();
    }
    

  2. Now call this method on the onClick of the overlay you created.

  3. What we want now is to make the overlay visible when you press on the editText. You cannot use the onFocus event (at least I did not get it to work...) So what i did is I managed the onTouch event instead.

editText.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(final View v, final MotionEvent event) {
    keyboardOverlay.setVisibility(View.VISIBLE);
    editText.requestFocus();
    return false;
}

});

The requestFocus() here is to not override the focus event with the onTouch.

Quick advice, when you try this out, you can add a background color to the overlay to see exactly what is happening.

Hope it works for you!

Solution 8 - Android

set in a button or any view: this.getCurrentFocus().clearFocus(); For example:

@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    this.getCurrentFocus().clearFocus();
    return super.onMenuOpened(featureId, menu);
}

Solution 9 - Android

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;
	}
});

	
	

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustCuriousView Question on Stackoverflow
Solution 1 - AndroidSudhanshu GaurView Answer on Stackoverflow
Solution 2 - AndroidlynnyiluView Answer on Stackoverflow
Solution 3 - AndroidwoodshyView Answer on Stackoverflow
Solution 4 - AndroidRajul GoelView Answer on Stackoverflow
Solution 5 - AndroidKaushik NPView Answer on Stackoverflow
Solution 6 - AndroidSergei MaleevView Answer on Stackoverflow
Solution 7 - AndroidCharlesView Answer on Stackoverflow
Solution 8 - Androidnobjta_9x_tqView Answer on Stackoverflow
Solution 9 - AndroidSumitkView Answer on Stackoverflow