15

I tried to remove focus from empty editText but it isn't working correctly. I called clearFocus() on edittext ,and then I placed break point at my onFocusChanged() function call.

Here is what happened: onFocusChanged() called 4 times with the focused parameters values false,true,false,true.

What I thought was that onFocusChanged() must be called only once (with focused = false)

Sorry for my bad English. Any help would be appreciated. Thanks

Vijay
  • 545
  • 1
  • 5
  • 15

3 Answers3

25

In xml, make parent layout

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

and then call clearFocus on edit text and then call parent request focus

 mFragmentBase.editText.clearFocus();
 mFragmentBase.parentLayout.requestFocus();
Alok Gupta
  • 1,806
  • 22
  • 21
  • This worked perfectly. I couldn't get my edittext's focus to clear but when requesting parentLayout focus after, it worked! Thanks – DIRTY DAVE Dec 28 '21 at 17:20
24

This is happening because your EditText is the first focusable view.

From the docs,

Note: When a View clears focus the framework is trying to give focus to the first focusable View from the top. Hence, if this View is the first from the top that can take focus, then all callbacks related to clearing focus will be invoked after which the framework will give focus to this view.

You can try setting a dummy focusable view above the EditText to clear the focus from it.

pratZ
  • 3,078
  • 2
  • 20
  • 29
1

Instead of clearing the focus from EditText create an empty view at the top of the layout

<LinearLayout
    android:id="@+id/focusableLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:focusable="true"
    android:focusableInTouchMode="true"/>

and declare a utility function to hide the keyboard like this

fun hideKeyboard(activity: Activity) {
    val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager 
    inputMethodManager.hideSoftInputFromWindow(activity.currentFocus?.windowToken, 0)
}

Finally when you need to clear focus just call

focusableLayout.requestFocus()
hideKeyboard(currentActivity)
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
  • Welcome to Stack Overflow! Please note you are answering a very old and already answered question. Here is a guide on [How to Answer](http://stackoverflow.com/help/how-to-answer). – help-info.de Aug 13 '20 at 10:47