Cusom event attributes in android: onMyEvent binding application

Is there a way to connect a user onSomeEventListenerto an attribute using a binding library? The examples given for onClickare simple, and all of them use the prefix 'on' and listeners of the interface of one method, as well as the prefix 'add' and more complex scripts?

Imagine that I want to use my own connection logic on RecyclerView.addOnItemTouchListener , defining a child view, was affected by SimpleOnItemTouchListener.onTouchEvent and pass it to my view model, how can I achieve this?

I want to get something like this:

<RecyclerView
    app:onItemTouch="@{handlers::recyclerViewOnItemTouch}"/>

public class Handlers {
    public void recyclerViewOnItemTouch(View view) { ... }
}

Is there something similar to the approach when notifying the required structure of your custom property update using the BindingAdapter and InverseBindingListener ?

@BindingAdapter("app:someAttrChanged") 
public static void setListener(View view, InverseBindingListener listener)
+3
source share
1 answer

After some research and testing and errors, I found a solution.

Of course, you need to activate Bindingin Activityor Fragmentand set up an instance for it ClickHandlerand have a variable for it in xmlfor ClickHandler. Assuming you already know this, I will continue:

One piece of magic is used app:addOnItemTouchListenerfor RecyclerView:

<android.support.v7.widget.RecyclerView
    android:id="@+id/rec_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:addOnItemTouchListener="@{clickHandler.touchListener}"/>

The other part is ClickHandler.class:

public class ClickHandler {

    public RecyclerView.OnItemTouchListener touchListener;

    public ClickHandler(){
        //initialize the instance of your touchListener in the constructor
        touchListener = new RecyclerView.SimpleOnItemTouchListener(){
            @Override
            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e)     {
                //allow clicks
                return true;
            }

            @Override
                public void onTouchEvent(RecyclerView rv, MotionEvent e) {
                //check if it is working / check if we get the touch event:
                Log.d("onTouchEvent", "RecView: " + rv.getId() + "\nMotionEvent: "+ e.getAction());
            }
        };
    }

    /* last but not least: a method which returns the touchlistener. 
       You can rename the method, but don't forget to rename the attribute in the xml, too. */
    public RecyclerView.OnItemTouchListener touchListener(){
        return touchListener;
    }
}
+1
source

Source: https://habr.com/ru/post/1654212/


All Articles