Привязка данных - установить атрибут в нуль - PullRequest
0 голосов
/ 29 апреля 2018

У меня странная проблема с библиотекой привязки данных в Android. В моем приложении todo я хочу использовать двустороннюю привязку данных для формы добавления задачи. Это моя модель, которая вставляется в макет вида.

public class TaskFormModel extends BaseObservable {

private String title;
private String notes;
private String categoryUUID;

public Date dueDate;


public TaskFormModel() {
}

public TaskFormModel(String title, String notes, String categoryUUID, Date dueDate) {
    this.title = title;
    this.notes = notes;
    this.categoryUUID = categoryUUID;
    this.dueDate = dueDate;
}

/**
 * Resets the current object
 */
public void reset() {
    title = null;
    notes = null;
    categoryUUID = null;
    dueDate = null;

    notifyPropertyChanged(BR.title);
    notifyPropertyChanged(BR.notes);
    notifyPropertyChanged(BR.categoryUUID);
    notifyPropertyChanged(BR.dueDate);
    notifyPropertyChanged(BR.showError);
}

/**
 * Determines if an error should be shown or not
 *
 * @return True if title is not null, but is empty. False otherwise
 */
@Bindable
public boolean isShowError() {
    return title != null && title.trim().isEmpty();
}

@Bindable
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
    notifyPropertyChanged(BR.title);
    notifyPropertyChanged(BR.showError);
}
...

}

В моем макете я ссылаюсь на модель, как показано в следующем фрагменте

<data>
    <variable
        name="taskFormModel"
        type="de.einfachmachen.ui.addtask.form.TaskFormModel" />
</data>

<android.support.constraint.ConstraintLayout
    android:id="@+id/task_overview_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <TextView
        android:id="@+id/headline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Headline"
        android:text="@string/headline_add_task"/>


    <android.support.design.widget.TextInputLayout
        android:id="@+id/task_title_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/EditText"
        app:errorEnabled="true"
        app:error='@{taskFormModel.showError ? @string/error_task_title_missing : null}'
        app:hintTextAppearance="@style/TextFloatLabelAppearance"
        app:errorTextAppearance="@style/TextErrorAppearance"
        android:layout_marginLeft="@dimen/spacing_large"
        android:layout_marginRight="@dimen/spacing_large"
        android:layout_marginBottom="@dimen/spacing_large"
        app:layout_constraintTop_toBottomOf="@id/headline">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/task_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/Text"
            android:inputType="textCapSentences"
            android:lines="1"
            android:text="@={taskFormModel.title}"
            android:hint="@string/form_hint_title"/>
    </android.support.design.widget.TextInputLayout>

    ...

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/spacing_big"
        android:backgroundTint="@color/white"
        android:src="@mipmap/ic_launcher"
        app:fabSize="normal"
        app:borderWidth="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:rippleColor="@color/ripple_grey"/>

</android.support.constraint.ConstraintLayout>

Если пользователь нажимает FloatingActionButton, задача сохраняется в базе данных, а TaskFormModel сбрасывается с помощью метода reset. Как видите, метод reset устанавливает атрибуты класса равными null, а затем использует notifyPropertyChanged для обновления представления. Пока все отлично работает.

Но если я проверю атрибуты TaskFormModel после вызова метода reset, значения не будут установлены на null, они имеют значение пустой строки. И из-за этого метод isShowError возвращает true, что приводит к отображению пользователю ошибки формы. Это нежелательное поведение.

Так нельзя ли установить атрибут класса в нуль с привязкой данных? Кто-нибудь испытывал такое же поведение и знает, как решить проблему? Заранее спасибо.

p.s .: Я также пытался установить совершенно новый TaskFormModel для привязки с binding.setTaskFormModel(new TaskFormModel());. К сожалению, успеха не было.

...