How to create focus change listener with data binding

时间:2018-12-19 11:10:47

标签: android android-databinding android-mvvm

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

2 个答案:

答案 0 :(得分:0)

如果您这样编写Handler类,它将起作用:

public class Handler {

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

}

和您的布局如下:

<layout>

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

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

</layout>

不要忘记在Fragment或Activity中设置处理程序变量:

binding.setHandler(new Handler())

答案 1 :(得分:0)

上面的代码工作正常。我没有在布局的xml中添加与true对应的clickable equals。