Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create focus change listener with data binding

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}"/>
like image 363
Sam Avatar asked Oct 11 '25 13:10

Sam


1 Answers

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!