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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With