Android数据绑定-参考视图



我在我的新应用程序中使用android的数据绑定库。目前,我试图将另一个视图的引用传递给一个方法。

有一个ImageButton和一个onClickListener。在这个onClick侦听器中,我想将根视图的引用传递给方法。

<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>

上面提供的源代码只是一个示例,而不是完整的。还有更多的子元素,而且image按钮不是根元素的直接子元素。但我认为意思很清楚。

我已经尝试通过指定根视图的id来传递引用(见上文)。但这行不通。如果我试图编译这个,我得到错误,root_element的类型没有指定。

我还尝试导入生成的绑定类,并通过其中的公共字段访问根元素。这个方法也不起作用,因为绑定类必须先生成。

有没有办法传递一个视图的引用给一个方法?我知道我可以用@id/root_element传递根视图的id,但我不希望这样,因为我必须找到一种方法,仅使用给定的id获取对该视图的引用。

你可以使用root_element,但是Android Data Binding会使用大小写。因此,root_element变成了rootElement。你的处理程序应该是:

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

你所拥有的和你应该做的之间的区别是,不要传递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"
            ... />
.../>
因此,正如您可以看到的那样,在我的代码中,我获得了对switch的引用,并将其作为绑定中的变量传递进去。然后在我的布局中,我可以访问它,在lambda中传递它

你应该传递你想引用的元素的id。

<data>
    <variable
        name="viewModel"
        type=".....settings.SettingsViewModel" />
</data>
.
.
.
<Switch
        android:id="@+id/newGamesNotificationSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@{viewModel.getSubscriptionsValues(newGamesNotificationSwitch)}" />

看到开关id是newGamesNotificationSwitch,这就是我传递给getSubscriptionsValues(..)函数。

如果你的id有下划线(_),你应该使用camelcase传递它。

如:my_id_with_underscore应该作为myIdWithUnderscore传递。

希望有所帮助

最新更新