如何优雅的快速搭建MVVM项目-MVVMFramework系列教程(四)

获取列表数据并显示已经通过BaseRecyclerViewModel实现了,但是列表还不支持下拉刷新功能,所以我们还必须通过Databinding双向绑定来把ViewModel的refreshing和xml的SwipeRefreshLayout控件进行绑定。

BaseRefreshRecyclerViewModel

BaseRefreshRecyclerViewModel 其实 只需要实现OnRefreshListener 并且在onRefresh里面调用onListRefresh函数即可。
然后通过BindingConfig进行双向绑定桥接

    @InverseBindingAdapter(attribute = "refreshing",event = "refreshingAttrChanged")
    public static boolean isRefreshing(SwipeRefreshLayout view) {
        return view.isRefreshing();
    }


    @BindingAdapter("refreshing")
    public static void setRefreshing(SwipeRefreshLayout view, boolean refreshing) {
        if (refreshing != view.isRefreshing()) {
            view.setRefreshing(refreshing);
        }
    }
    @BindingAdapter(value = {"onRefreshListener", "refreshingAttrChanged"}, requireAll = false)
    public static void setOnRefreshListener(final SwipeRefreshLayout view,
                                            final SwipeRefreshLayout.OnRefreshListener listener,
                                            final InverseBindingListener refreshingAttrChanged) {

        SwipeRefreshLayout.OnRefreshListener newValue = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (listener != null) {
                    if (refreshingAttrChanged != null) {
                        refreshingAttrChanged.onChange();
                    }
                    listener.onRefresh();
                }
            }
        };

        SwipeRefreshLayout.OnRefreshListener oldValue = ListenerUtil.trackListener(view, newValue, R.id.onRefreshListener);
        if (oldValue != null) {
            view.setOnRefreshListener(null);
        }
        view.setOnRefreshListener(newValue);
    }

然后跟上一章一样,写一个通过的layout 用于 include ,include_recyclerview_refresh.xml 如下:




    

        
        
        
        
    


    

        
    


使用起来和上一章一样,在具体的xml中include include_recyclerview_refresh.xml,然后ViewModel继承BaseRefreshRecyclerViewModel,即可下拉刷新。

Github

MVVMFramework

你可能感兴趣的:(如何优雅的快速搭建MVVM项目-MVVMFramework系列教程(四))