Почему ссылка на представление, использующее класс привязки, помечена @Nullable?

#android #xml #android-viewbinding #kotlin-null-safety

Вопрос:

У меня есть макет с некоторым видом текста и видом карты. Только ссылка binding.mycardview возвращает объект CardView? , но в соответствии с документами:

Безопасность Null: Поскольку привязка представления создает прямые ссылки на представления, нет риска исключения нулевого указателя из-за недопустимого идентификатора представления. Кроме того, если представление присутствует только в некоторых конфигурациях макета, поле, содержащее его ссылку в классе привязки, помечается @Nullable.

Мой макет row.xml:

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@ id/cVComune"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/space"
        android:layout_marginTop="@dimen/space"
        android:layout_marginEnd="@dimen/space"
        android:layout_marginBottom="@dimen/space"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@ id/tvComune"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/space"
                android:layout_marginTop="@dimen/space"
                android:textSize="@dimen/text_label_medium"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@ id/tvCap"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/space"
                android:layout_marginTop="@dimen/space"
                android:textSize="@dimen/text_label_medium"
                app:layout_constraintStart_toEndOf="@ id/ivMail"
                app:layout_constraintTop_toBottomOf="@ id/tvComune" />

            <TextView
                android:id="@ id/tvPrefisso"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/space"
                android:layout_marginTop="@dimen/space"
                android:textSize="@dimen/text_label_medium"
                app:layout_constraintStart_toEndOf="@ id/ivPhone"
                app:layout_constraintTop_toBottomOf="@ id/tvComune" />

            <TextView
                android:id="@ id/tvAbitanti"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/space"
                android:layout_marginTop="@dimen/space"
                android:textSize="@dimen/text_label_medium"
                app:layout_constraintStart_toEndOf="@ id/ivAbitanti"
                app:layout_constraintTop_toBottomOf="@ id/tvComune" />

            <TextView
                android:id="@ id/tvLink"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/space"
                android:layout_marginTop="@dimen/space"
                android:textColor="@color/hyperlink"
                android:textSize="@dimen/text_label_medium"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@ id/tvCap" />

            <TextView
                android:id="@ id/tvProvincia"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/space"
                android:layout_marginEnd="@dimen/space"
                android:textSize="@dimen/text_label_medium"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@ id/tvRegione"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/space"
                android:layout_marginEnd="@dimen/space"
                android:textSize="@dimen/text_label_medium"
                app:layout_constraintEnd_toStartOf="@ id/tvProvincia"
                app:layout_constraintTop_toTopOf="parent" />

            <ImageView
                android:id="@ id/ivMail"
                android:layout_width="@dimen/widthimg"
                android:layout_height="0dp"
                android:layout_marginStart="@dimen/space"
                android:layout_marginTop="@dimen/space"
                android:contentDescription="@string/codicepostale"
                app:layout_constraintBottom_toBottomOf="@ id/tvCap"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@ id/tvComune"
                app:layout_constraintVertical_bias="0.3"
                app:srcCompat="@drawable/mail" />

            <ImageView
                android:id="@ id/ivPhone"
                android:layout_width="@dimen/widthimg"
                android:layout_height="0dp"
                android:layout_marginStart="@dimen/spaceimg"
                android:layout_marginTop="@dimen/space"
                android:contentDescription="@string/telefono"
                app:layout_constraintBottom_toBottomOf="@ id/tvCap"
                app:layout_constraintStart_toEndOf="@ id/ivMail"
                app:layout_constraintTop_toBottomOf="@ id/tvComune"
                app:layout_constraintVertical_bias="0.0"
                app:srcCompat="@drawable/phone" />

            <ImageView
                android:id="@ id/ivAbitanti"
                android:layout_width="@dimen/widthimg"
                android:layout_height="0dp"
                android:layout_marginStart="@dimen/spaceimg"
                android:layout_marginTop="@dimen/space"
                android:contentDescription="@string/abitanti"
                app:layout_constraintBottom_toBottomOf="@ id/tvPrefisso"
                app:layout_constraintStart_toEndOf="@ id/ivPhone"
                app:layout_constraintTop_toBottomOf="@ id/tvComune"
                app:layout_constraintVertical_bias="0.0"
                app:srcCompat="@drawable/stick" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>
 

Итак, почему RowBinding.tvLink объект TextView помечен @NonNull , но RowBinding.cVComune является CardView? помеченным @Nullable ? Это ошибка?

Ответ №1:

У вас есть несколько версий row.xml ? Например, res/layout/row.xml и res/layout-land/row.xml ? Если CardView этот атрибут отсутствует в одном из двух файлов макета или если его нет android:id в представлении карты, его тип будет допускаться к значению null.

Вы должны иметь возможность просматривать сгенерированный файл привязки в Android Studio, заглянув в build/generated/data_binding_base_class_source_out каталог вашего модуля. В этом файле должен быть комментарий, объясняющий, почему представление может быть аннулировано.

Например, здесь я удалил android:id атрибут из моего TextView в layout-land версии моего файла макета:

   /**
   * This binding is not available in all configurations.
   * <p>
   * Present:
   * <ul>
   *   <li>layout/</li>
   * </ul>
   *
   * Absent:
   * <ul>
   *   <li>layout-land/</li>
   * </ul>
   */
  @Nullable
  public final TextView text;