Android 数据绑定 - 参考视图

Android Data Binding - Reference to view

我在我的新应用程序中使用 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>

上面提供的源代码只是一个例子,并不完整。 有更多的子元素,图像按钮也不是根元素的直接子元素。不过我觉得意思很清楚。

我已经尝试通过指定根视图的 ID 来传递引用(见上文)。但这不起作用。如果我尝试编译它,我会收到错误消息,未指定 root_element 的类型。

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

那么有什么方法可以将视图的引用传递给方法吗? 我知道我可以使用 @id/root_element 传递根视图的 ID,但我不想那样,因为我必须找到一种方法来仅使用给定的 ID 来获取对该视图的引用。

你拥有的和你应该做的之间的区别在于,不要传递 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 中传递它。

您可以使用 root_element,但 Android 数据绑定对名称进行驼峰式命名。因此,root_element 成为 rootElement。您的处理程序应该是:

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

您应该传递要引用的元素的 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 有一些下划线 (_),您应该使用驼峰式命名法传递它。

例如: my_id_with_underscore 应作为 myIdWithUnderscore 传递。

希望对您有所帮助