Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Android Lists and Adapters Displaying Lists of Data Creating a Custom Layout

Problems understanding the xml code

Hi, I don't understand the usage of <data> , <variable> and the line "android:text="@{String.valueOf(hour.time)}" " in the xml code, could you please help me? Perhaps provide me some links, thanks!

1 Answer

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,795 Points

Tomás Borges sorry for the late reply.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="hour"
            type="com.androidshowtime.stormy.weather.Hour" />
    </data>

    <RelativeLayout>

        <TextView
            android:id="@+id/timeLabel"
            android:text="@{String.valueOf(hour.time)}"
            android:textSize="24sp" />

Data Binding enables you to bind UI elements in your layouts to data sources in your app using a declarative style rather than programmatically. data-binding xml layout files are slightly different and must start with a root tag of layout followed by a <data> element and a view root element in this case it is the Relative Layout.

<data>
        <variable name="hour"
           type="com.androidshowtime.stormy.weather.Hour" />
    </data>

The hour variable declared within data tag describes the property to be used within this layout.

<TextView
            android:id="@+id/timeLabel"
            android:text="@{String.valueOf(hour.time)}"
            android:textSize="24sp" />

If you want to use expressions inside your layout, you can call attribute properties using the ** “ @{}" ** syntax. In the example above, the TextView text is set to the time property of the hour variable

I trust this clarifies.

Thanks,

Tonnie