查看模型不更新UI

时间:2018-04-16 05:16:22

标签: android mvvm data-binding

我有以下课程

PostsViewModel.java

......
//Boolean observable to toggle the visibility of progress bar
public static final ObservableBoolean postsLoading = new ObservableBoolean(false);

private void getPosts() {
    postsLoading.set(true);
    getPostRepository().getPosts(new PostDataSource.LoadPostCallback() {
        @Override
        public void onPostsLoaded(List<Post> posts) {
            boolean isEmpty = posts == null || posts.isEmpty();

            //setting the post loading false here
            postsLoading.set(false);

            Log.d(TAG, "onPostsLoaded: posts loading set to false");
            if (!isEmpty) {
                mPostObservable.clear();
                mPostObservable.addAll(posts);
            }
            errorViewShowing.set(isEmpty);

        }

        @Override
        public void onDataNotAvailable(String message) {
            postsLoading.set(false);
            errorViewShowing.set(true);
            errorString.set(message);
        }
    });
}
......

PostActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PostList binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    PostsViewModel mPostsViewModel = new PostsViewModel();
    binding.setPostViewModel(mPostsViewModel);
    mPostsViewModel.getPosts(); //calling get posts here
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data class="PostList">

    <import type="android.view.View" />

    <variable
        name="postViewModel"
        type="com.example.vuclip.mvvm_repository.posts.PostsViewModel" />
</data>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".posts.PostsActivity">

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="@{ postViewModel.postsLoading ? View.VISIBLE : View.GONE }" />

</RelativeLayout>
</layout>

我想根据postsLoadingPostsViewModel ObservableBoolean变量的值切换进度条的可见性。我使用调试器检查并确认我的代码确实将postsLoading变量的值设置为false但仍然可以看到进度条。

看起来Observable字段中的更改由于某种原因未通知布局文件。我在这里弄错了什么?

我在gradle文件中启用了dataBinding。

1 个答案:

答案 0 :(得分:0)

问题是我的Observable字段是静态的。我真的不知道为什么会这样,但是一旦我删除静态字段,它就会开始工作。