Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why generated ViewDataBinding class annotates property for "include" tag as Nullable

I'm using Android Data Binding library to bind an xml layout that has an <include>

layout.xml

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

    <data>
        <variable
            name="model"
            type="com.example.MyViewModel" />
    </data>

    ...

    <include
        layout="@layout/someOtherLayout"
        android:id="@+id/includedLayout" />
    ...

</layout>

In the generated Databinding class for the xml I see this property:

@Nullable
public final com.example.databinding.SomeOtherLayoutBinding includedLayout;

Why is it annotated as @Nullable? The <include> is in the layout and as I see it, it is obviously non-null. What am I missing?

It forces me to use non-null assertion operator !! in Kotlin code when accessing the fields of the included layout and I'm wondering if it is safe or if there is something I'm not considering here

val binder = DataBindingUtil.bind(view)
val someView = binder.includedLayout!!.someView
like image 981
lelloman Avatar asked Mar 14 '18 12:03

lelloman


People also ask

How do I stop findViewById in Kotlin?

Kotlin Android Extensions is a great way to avoid writing findViewById in the activity or fragment. Simply, add the kotlin-android-extensions plugin to the module level build. gradle file.

How would you enable view binding for a module in your application so you can reference views from layout files without using findViewById?

To enable view binding, configure viewBinding in your module-level build. gradle file. Once enabled for a project, view binding will generate a binding class for all of your layouts automatically. You don't have to make changes to your XML — it'll automatically work with your existing layouts.

What is DataBindingUtil in Android?

DataBindingUtil.setContentView(this, R.layout.activity_main) DataBindingUtil is a Utility class to create ViewDataBinding from layouts. A binding class is generated for each layout file. The default naming convention used for the generated class is based on the name of the layout file.


1 Answers

According to the Documentation on View Binding, when you have multiple layouts for configuration changes, if the view is only present in some configurations, the binding class will be marked as nullable.

View Binding Docs

like image 161
Paixols Avatar answered Oct 16 '22 23:10

Paixols