1

I am using following code for EditText focus change event and its working when I tap on one EditText to another EditText but fails when we tap outside the EditText .I have already added focusable="true"and focusableInTouchMode="true" but it does not work.

@BindingAdapter("onFocusChange")
public static void onFocusChange(EditText 
text, final View.OnFocusChangeListener 
listener) {
   text.setOnFocusChangeListener(listener);
}

public class Handler {
   public View.OnFocusChangeListener 
      getOnFocusChangeListener() {
           return new 
   View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View 
                  view, boolean isFocussed
          {
            //Hide Keyboard
           }
          };
        }
     }

 <data>
  <variable name="handler" type="Handler"/>
</data>
<EditText app:onFocusChange="@{handler.OnFocusChangeListener}"/>
Milad Bahmanabadi
  • 1,043
  • 11
  • 21
Sam
  • 453
  • 5
  • 19

2 Answers2

3

It should work if you write your Handler class like this:

public class Handler {

    public OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean isFocused) {
            //Hide Keyboard
        }
    };

}

and your layout like this:

<layout>

    <data>
        <variable name="handler" type="Handler"/>
    </data>

    <EditText 
        ...
        app:onFocusChangeListener="@{handler.onFocusChangeListener}"
        ... />

</layout>

Don't forget to set the handler variable in the Fragment or Activity:

binding.setHandler(new Handler())
janosch
  • 1,848
  • 14
  • 25
  • Its working but when I tap outside the EditText keyboard does not collapsed.One more think I have already added binding.setHandler(new Handler()) in activity – Sam Dec 20 '18 at 06:57
  • Yeah you still need to add the hide keyboard logic, which is a topic by itself: https://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard – janosch Dec 20 '18 at 08:25
  • Already added the logic.Point is when I touch the screen outside Edittext the focus is not getting lost – Sam Dec 20 '18 at 09:07
  • Your EditText only looses focus when something else gets focused, like when touching another EditText, not when you press anywhere outside of the EditText on something that can not be focused. – janosch Dec 20 '18 at 09:16
  • Screen can be made focusable – Sam Dec 20 '18 at 09:23
0

Above code works fine.I had not added clickable equals to true in the xml for the layout.

Sam
  • 453
  • 5
  • 19