Android data binding view.onTouchListener

Viewed 5196

Android in data binding there is

<Button android:onClick="@{handler.someButtonClick()}"/>

and in its Handler class its listener will be some how like:

public View.OnClickListener someButtonClick() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        };
    }

I want to implement OnTouchListener for a Button that I could know that when the button is pressed and when it is released

Like:

// Check if the button is PRESSED
if (event.getAction() == MotionEvent.ACTION_DOWN){
     //do some thing          
}// Check if the button is RELEASED
else if (event.getAction() == MotionEvent.ACTION_UP) {
    //do some thing                     
}

Is there any possible way to accomplish this task.

3 Answers

ViewModel

public class RecyclerViewModel   {
      public View.OnTouchListener onTouchListener;

      public void setOnTouchListener( View.OnTouchListener onTouchListener) {
          this.onTouchListener = onTouchListener;
      }
}

DataBinding

@BindingAdapter("onTouchListener")
public static void setOnTouchListener(View view, View.OnTouchListener onTouchListener) {
    if (onTouchListener != null)
        view.setOnTouchListener(onTouchListener);
}

Use in xml

<Button app:onTouchListener="@{viewModel.onTouchListener}"/>

ViewModel

private var tapTime: Long = 0

fun onTouchListener(view:View, event: MotionEvent): Boolean {
   when (event.action) {
      MotionEvent.ACTION_DOWN -> {
          tapTime = Date().time
          // more commands for touch down event
      } 
      MotionEvent.ACTION_UP -> {
         if (Date().time - tapDate < 300) {
            view.performClick()
           // more commands if click event
         } else {
           // any commands if holded toch on screen
         } 
     }
  }
  return true
}

No need for data binding adapter. It exists already.

XML

<Button
   ...
   app:onTouchListener="@{viewModel.onTouchListener}"
   ...
  />

Warning You need to use the right signature in ViewModel:

fun name(view:View, event: MotionEvent): Boolean

and right name of the attribute in XML:

app:onTouchListener
Related