Search code examples
androiddata-bindingontouchlistener

Android data binding view.onTouchListener


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.


Solution

  • Here is a workaround which you can use to do this.

    @BindingAdapter("touchListener")
    public void setTouchListener(View self,boolean value){
        self.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                // 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
                }
                return false;
            }
        });
    }
    

    And then in xml

    <Button  app:touchListener="@{true}"/>