我在我的新应用中使用了android的数据绑定库。 目前我尝试将另一个视图的引用传递给方法。我有一个ImageButton
onClickListener
。在这个onClick监听器中,我想将根视图的引用传递给方法。Android数据绑定 - 引用视图
<RelativLayout
android:id="@+id/root_element"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:contentDescription="@string/close_dialog"
android:src="@drawable/ic_close_212121_24dp"
android:background="@android:color/transparent"
android:onClick="@{() -> Helper.doSth(root_element)}"/>
</RelativLayout>
上面提供的这个源代码仅仅是一个例子,而不是完整的。 有更多的孩子,也是图像按钮不是根元素的直接子。但我认为其含义很明确。
我已经尝试通过指定根视图的ID来传递引用(参见上文)。但这不起作用。如果我试图编译这个,我得到的错误,没有指定root_element
的类型。
我也尝试导入生成的绑定类,并通过它中的公共字段访问根元素。此方法也不起作用,因为必须首先生成绑定类。
那么有没有办法将视图的引用传递给方法? 我知道我可以通过@id/root_element
来传递根视图的id,但是我不想这样做,因为我必须找到一种方法来只使用给定的id来获得对此视图的引用。
我认为这应该是答案。使用Google文档更简单并且坚持不懈。 对于人们想要更多信息,他们可能会参考下面的答案和Google IO 2016. http://stackoverflow.com/questions/37727600/cannot-refer-to-other-view-id-in-android-data-binding https://www.youtube.com/watch?v=DAmMN7m3wLU&feature=youtu.be&t=13m59s – OnJohn
这个答案是正确的。无论何时使用数据绑定来传递视图元素。这是默认情况下骆驼。 –