Home > Mobile >  Viewbinding shows nullable view also crashing app when screen rotets
Viewbinding shows nullable view also crashing app when screen rotets

Time:01-16

Here is my view in xml

<androidx.appcompat.widget.AppCompatEditText
    android:id="@ id/et_user_name"
    style="@style/text_bold"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginStart="@dimen/_8sdp"
    android:layout_weight="1"
    android:backgroundTint="@color/activity_background_color"
    android:cursorVisible="false"
    android:maxLines="1"
    android:imeOptions="actionDone"
    android:minHeight="48dp"
    android:padding="@dimen/_6sdp"
    android:text="@string/guest_user"
    android:textColor="@color/text_color_dark"
    android:textSize="@dimen/_18sdp" />

here is my setText method

mView.etUserName!!.setText(sharePrefHelper.user?.name)

Here is init of mView

private lateinit var mView: FragmentProfileBinding
mView = FragmentProfileBinding.inflate(inflater)

this happens some of XML views most views are non nullable but some views are shown as nullable don't know what cause this issue

CodePudding user response:

As per the View Binding documentation:

Null safety: Since view binding creates direct references to views, there's no risk of a null pointer exception due to an invalid view ID. Additionally, when a view is only present in some configurations of a layout, the field containing its reference in the binding class is marked with @Nullable.

If you have a nullable field in your binding, that means you have another configuration (for example, one in res/layout-land or some other folder) that does not contain a view with that android:id.

As soon as you add that View with the android:id to each configuration of that layout, it will no longer be nullable. The other option is to remove the alternate versions of that layout and use the same layout in all configurations.

  • Related