3

有没有办法onSomeEventListener使用绑定库将自定义连接到属性?提供的例子onClick很简单,都使用'on'前缀和单方法接口监听器,那么'add'前缀和更复杂的场景呢?

想象一下,我想在RecyclerView.addOnItemTouchListener上使用自定义连线逻辑,确定从SimpleOnItemTouchListener.onTouchEvent触摸子视图并将其传递给我的视图模型,我该如何实现?

我想结束这样的事情:

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

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

在使用 BindingAdapter 和InverseBindingListener通知绑定框架有关您的自定义属性更新时,是否有类似的方法?

@BindingAdapter("app:someAttrChanged") 
public static void setListener(View view, InverseBindingListener listener)
4

1 回答 1

1

经过一番调查和反复试验,我找到了解决方案。

当然,您需要Binding在您的Activityor中激活Fragment并为其设置一个实例ClickHandler,并在您的xmlfor中为其设置一个变量ClickHandler。假设您已经知道,我将继续:

魔法的一部分是app:addOnItemTouchListener用于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}"/>

另一部分是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;
    }
}
于 2016-07-05T07:19:59.487 回答