经过一番调查和反复试验,我找到了解决方案。
当然,您需要Binding
在您的Activity
or中激活Fragment
并为其设置一个实例ClickHandler
,并在您的xml
for中为其设置一个变量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;
}
}