Android Data Binding - Reference to view

You should pass the id of the element you want to reference.

<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)}" />

See that the switch id is newGamesNotificationSwitch and thats what i am passing into getSubscriptionsValues(..) function.

In case your id has some underscores (_) you should pass it using camelcase.

Eg: my_id_with_underscore should be passed as myIdWithUnderscore.

Hope it helps


The difference between what you have and what you should do is, don't pass the id root_element. Rather, pass through the view as another variable into the layout file.

In my case, I had a switch in my layout, that I wanted to pass as a parameter to a method in my lambda. My code is like this:

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

Then my layout is like this:

<?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"
            ... />
.../>

So as you can see with this, in my code, I get the reference to my switch and pass it in as a variable in the binding. Then in my layout I then have access to it, to pass it through in my lambda.


You can use root_element, but Android Data Binding camel-cases the names. So, root_element becomes rootElement. Your handler should be:

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