2016-06-28 59 views
7

我在我的新应用中使用了android的数据绑定库。 目前我尝试将另一个视图的引用传递给方法。我有一个ImageButtononClickListener。在这个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来获得对此视图的引用。

回答

4

你有什么和你应该做什么之间的区别是,不要通过ID root_element。相反,将视图作为另一个变量传递到布局文件中。

在我的情况下,我在布局中有一个开关,我想作为参数传递给lambda中的方法。我的代码是这样的:

MyLayoutBinding binding = DataBindingUtil.inflate(inflater, R.layout.my_layout, parent, true); 
binding.setDataUpdater(mDataUpdater); 
binding.setTheSwitch(binding.switchFavorite); 

然后我的布局是这样的:

<?xml version="1.0" encoding="utf-8"?> 
<layout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 
    <data> 
     <variable name="dataUpdater" type="..."/> 
     <variable name="theSwitch" type="android.widget.Switch"/> 
     <import type="android.view.View"/> 
    </data> 
    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:onClick="@{()->dataUpdater.doSomething(theSwitch)}"> 
     <Switch 
      style="@style/Switch" 
      android:id="@+id/switch_favorite" 
      ... /> 
.../> 

所以你可以用这个看到,在我的代码,我得到的引用我的开关,并通过它在作为绑定中的一个变量。然后在我的布局中,我可以访问它,在我的lambda中传递它。

34

您可以使用root_element,但Android数据绑定骆驼案件的名称。所以,root_element变成了rootElement。你的处理程序应该是:

android:onClick="@{() -> Helper.doSth(rootElement)}" 
+2

我认为这应该是答案。使用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

+0

这个答案是正确的。无论何时使用数据绑定来传递视图元素。这是默认情况下骆驼。 –