0

I feel somewhat guilty asking, because there are so many questions about, but I couldn't find a solution.

How to make my (single) EditText lose focus when I touch outside? By focus I mean the view being ready to get input, with cursor visible. I would be ok with:

  • view losing focus when I touch on anything else (e.g., blank space outside);
  • view losing focus when I touch other views in my layout.

Now, answers mostly say how to reach the second goal, by adding a click listener to all other views. That would be possible but not the best way in my opinion.

As for the first (view losing focus as soon as you touch outside) lots of input came from:

A focusable view (such as this EditText) only loses focus when another focusable view gains it. Most views are not focusable by default.

Looked like the ultimate solution, but setting android:focusable (or focusable in touch mode) on other elements (tried on a RatingBar and a whole Layout) did nothing for me.

  • this question, where people came up with solutions involving getX() / getY() of the point of touch, and checking whether it was inside the edit text. I find that more complex than the problem itself, and rather discouraging if you have more than one edit text.

Is there anything else for a such common wish? Conceptually speaking, why if I give input to the EditText and tap on (e.g. on a rating bar) that view should be still focused and waiting, with its blinking cursor?

Community
  • 1
  • 1
natario
  • 24,954
  • 17
  • 88
  • 158

1 Answers1

3

You could be done with dispatchTouchEvent.

@Override
   public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
    if (mEditText.isFocused()) {
        Rect outRect = new Rect();
        mEditText.getGlobalVisibleRect(outRect);
        if (!outRect.contains((int)event.getRawX(),(int)event.getRawY()))   {
            mEditText.clearFocus();
            //
            // Hide keyboard
            //
            InputMethodManager imm = (InputMethodManager)    v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
         }
       }
     }
 return super.dispatchTouchEvent(event);
 }

It will be bit difficult to work with more number of edit texts. So I came across it when I had a similar issue and thought I'd share what I ended up doing.

The view that gained focus was different each time so I used the very generic:

 View current = getCurrentFocus();
 if (current != null) current.clearFocus();

You can call this in your dispatchTouchEvent.

King of Masses
  • 18,405
  • 4
  • 60
  • 77
  • This answer is actually linked in my question (see when I talk about getX() / getY() ) and as I said I was looking for a simpler solution. This gets painful if you have more than one edit text. – natario Feb 11 '15 at 13:37
  • I updated my code. you can check it and let me @m iav – King of Masses Feb 12 '15 at 05:15