Cusom事件属性在android绑定应用程序:onMyEvent [英] Cusom event attributes in android bindings app:onMyEvent
问题描述
有没有办法使用绑定库连接自定义 onSomeEventListener
到属性? onClick
很简单,他们都使用'on'前缀和单一方法接口侦听器,add前缀和更复杂的场景呢?
Is there any way to wire up custom onSomeEventListener
to the attribute using binding library? Examples provided for onClick
are simple and they all use 'on' prefix and single-method interface listeners, and what about 'add' prefix and more complicated scenarios?
想象一下,我想在 RecyclerView.addOnItemTouchListener ,确定子视图是从 SimpleOnItemTouchListener.onTouchEvent 并将其传递给我的视图模型,如何我可以实现吗?
Imagine I want to use custom wire up logic on RecyclerView.addOnItemTouchListener, determining the child view was touched from SimpleOnItemTouchListener.onTouchEvent and passing it to my view model, how can I achieve this?
我想要结束这样做:
<RecyclerView
app:onItemTouch="@{handlers::recyclerViewOnItemTouch}"/>
public class Handlers {
public void recyclerViewOnItemTouch(View view) { ... }
}
当使用BindingAdapter和 InverseBindingListener ?
Is there something similar to approach when notifying binding framework about your custom property update using BindingAdapter and InverseBindingListener?
@BindingAdapter("app:someAttrChanged")
public static void setListener(View view, InverseBindingListener listener)
推荐答案
经过一番调查和试错,我找到了一个解决方案。
After some investigation and trial and error, I found a solution.
当然,您需要在活动中激活
绑定
code>或 Fragment
并设置一个 ClickHandler
的实例,并为其添加一个变量 xml
为 ClickHandler
。假设你已经知道了,我会继续:
Of course, you'll need to activate the Binding
in your Activity
or Fragment
and set an instance of the ClickHandler
to it, and have a variable for it in your xml
for the ClickHandler
. Assuming that you already know that, I'll continue:
魔术的一部分是使用 app:addOnItemTouchListener
对于 RecyclerView
:
One part of the magic is using app:addOnItemTouchListener
for the 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;
}
}
这篇关于Cusom事件属性在android绑定应用程序:onMyEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!