Sam
Sam

Reputation: 621

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}"/>

Upvotes: 4

Views: 5038

Answers (2)

Sam
Sam

Reputation: 621

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

Upvotes: 0

anon
anon

Reputation:

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

Upvotes: 4

Related Questions