Is there a way to observe an Arraylist's size as it changes via databinding?

Viewed 3161

Basically my ViewModel holds the following POJO as a MutableLiveData:

public class SubredditAddition {

    private final ArrayList<Keyword> mKeywords = new ArrayList<>();

}

And I want a view to disappear if mKeyword.size() > 0

Currently, I have the following line in my view:

android:visibility="@{viewModel.subredditAddition.keywords.size() == 0 ? View.GONE : View.VISIBLE}"

However, changes to the mKeywords array size does not affect the view's visibility. How can I make the view react to the ArrayList's size in realtime?

Update:

My SubredditAddition class now uses ObservableArraylist, like so:

public class SubredditAddition {

    private final ObservableArrayList<Keyword> mKeywords = new ObservableArrayList<>();

}

My ViewModel looks like this, holding a SubredditAddition in a MutableLiveData:

public class SubredditSelectionViewModel extends AndroidViewModel {

    private MutableLiveData<SubredditAddition> mSubredditAddition = new MutableLiveData<>();

    public SubredditSelectionViewModel(Application application) {
        super(application);

        mSubredditAddition.setValue(new SubredditAddition());
    }
}

And my Fragment has the following code to update the keywords:

public class SubredditSelectionFragment extends Fragment {

    private void saveTag(Keyword newKeyword) {
        SubredditSelectionViewModel viewModel =
                ViewModelProviders.of(this).get(SubredditSelectionViewModel.class);

         ObservableArrayList<Keyword> keywords = viewModel.getSubredditAddition().getKeywords();

        keywords.add(newKeyword);
    }
}

My XML view looks like this:

<RelativeLayout ....
            android:visibility="@{viewModel.subredditAddition.keywords.size() == 0 ? View.VISIBLE : View.GONE}">

However, my UI still does not get updated once I add a keyword via the saveKeyword() method in my Fragment. How can I fix this?

1 Answers
Related