安卓DataBing解决问题

  • VM管理视图和数据
package com.vpgame.eric.main.articles;

import android.databinding.Bindable;
import android.databinding.ObservableBoolean;
import android.util.Log;
import android.view.View;

import com.vpgame.eric.BR;
import com.vpgame.eric.R;
import com.vpgame.eric.app.App;
import com.vpgame.eric.data.statistics.StatisticsEvent;
import com.vpgame.eric.data.statistics.StatisticsUtils;
import com.vpgame.eric.model.VPModel;
import com.vpgame.eric.model.conver.ApiDataSubscriber;
import com.vpgame.eric.model.conver.ApiSubscriber;
import com.vpgame.eric.model.conver.MoreDataBean;
import com.vpgame.eric.model.home.ArticlesBean;
import com.vpgame.eric.model.home.ArticlesDetailsBean;
import com.vpgame.eric.ui.base.BaseViewModel;
import com.vpgame.eric.utils.DialogUtils;
import com.vpgame.eric.utils.LogUtils;
import com.vpgame.eric.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import retrofit2.Response;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * @version V1.0
 * @author:asi
 * @date 2017/12/20 10:32
 * @desc: 描述这个类的作用
 */

public class ArticlesDetailsVM extends BaseViewModel {

    private String gameTitle;
    private DetailsAdapter mAdapter;

    private static final int LIMIT = 10;
    private int OFFSET = 0;
    private String mId;
    private ArticlesBean bean;

    // 使用ObservableBoolean
    public ObservableBoolean isLoading = new ObservableBoolean(true);

    public ArticlesDetailsVM(DetailsAdapter adapter, String id, String gameTitle) {
        mAdapter = adapter;
        mId = id;
        this.gameTitle = gameTitle;
    }

    void getHeadData() {
        Subscription subscribe = App.getVP2Api().getArticlesHead(mId)
                .subscribeOn(Schedulers.io())
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        isLoading.set(false);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiDataSubscriber<ArticlesBean>() {

                    @Override
                    public void onSuccess(ArticlesBean headBean) {
                        if (headBean != null) {
                            setBean(headBean);
                        }
                    }

                    @Override
                    public void onFail(String errMsg) {

                    }


                });
        addSubscription(subscribe);
    }

    void getArticleList() {
        OFFSET = 0;
        Subscription subscribe = App.getVP2Api().getArticlesDetailsList(mId, LIMIT, OFFSET)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiSubscriber<MoreDataBean<List<ArticlesDetailsBean>>>() {

                    @Override
                    public void onSuccess(MoreDataBean<List<ArticlesDetailsBean>> moreDataBean) {
                        if (moreDataBean != null) {
                            mAdapter.setNewData(moreDataBean.getData());
                        } else {
                            mAdapter.setEnableLoadMore(false);
                        }

                    }

                    @Override
                    public void onFail(String errMsg) {

                    }


                });
        addSubscription(subscribe);
    }

    void loadMoreList() {
        OFFSET = mAdapter.getData().size();
        Subscription subscribe = App.getVP2Api().getArticlesDetailsList(mId, LIMIT, OFFSET)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiSubscriber<MoreDataBean<List<ArticlesDetailsBean>>>() {

                    @Override
                    public void onSuccess(MoreDataBean<List<ArticlesDetailsBean>> moreDataBean) {
                        if (moreDataBean != null && moreDataBean.getData() != null && moreDataBean.getData().size() > 0) {
                            mAdapter.addData(moreDataBean.getData());
                            mAdapter.loadMoreComplete();
                        } else {
                            mAdapter.loadMoreEnd(true);
                        }

                    }

                    @Override
                    public void onFail(String errMsg) {
                        mAdapter.loadMoreFail();
                    }


                });
        addSubscription(subscribe);
    }


    /**
     * 第三方分享
     */
    public void showShare(View view) {
        StatisticsUtils.onEvent(getContext(), gameTitle + StatisticsEvent.VP_EVENT_NEWS_COLUMN_SHARE_BTN);
        DialogUtils.showShareDialog(getContext(), bean.getTitle(), bean.getSubtitle(), bean.getShare_link(), bean.getCover(), new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastUtils.showToast(getContext(), getContext().getResources().getString(R.string.ssdk_oks_share_completed));
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
            }

            @Override
            public void onCancel(Platform platform, int i) {

            }
        }, null, false, false);
    }

    /**
     * 订阅
     */
    public void onSubc(View view) {
        StatisticsUtils.onEvent(getContext(), gameTitle + StatisticsEvent.VP_EVENT_NEWS_COLUMN_DET_TAKE_BTN);
        if (!DialogUtils.isNeedShowLoginDialog(getContext()) && bean != null) {
            Subscription subscribe;
            if (bean.getSubscriber().isSubscribed()) {
                subscribe = App.getVP2Api().onUnSubscribeArticles(mId)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<Response<VPModel>>() {

                            @Override
                            public void onCompleted() {

                                bean.getSubscriber().setCount(bean.getSubscriber().getCount() - 1 < 0 ? 0 : bean.getSubscriber().getCount() - 1);
                                bean.getSubscriber().setIsSubscribed(false);
                                notifyPropertyChanged(BR.bean);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(Response response) {

                            }


                        });

            } else {
                subscribe = App.getVP2Api().onSubscribeArticles(mId)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<Response<VPModel>>() {

                            @Override
                            public void onCompleted() {

                                bean.getSubscriber().setCount(bean.getSubscriber().getCount() + 1);
                                bean.getSubscriber().setIsSubscribed(true);
                                notifyPropertyChanged(BR.bean);

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(Response response) {

                            }


                        });

            }
            addSubscription(subscribe);
        }


    }

    @Bindable
    public ArticlesBean getBean() {
        return bean;
    }

    public void setBean(ArticlesBean bean) {
        this.bean = bean;
        notifyPropertyChanged(BR.bean);
    }
}
  • 请求和逻辑代码修改放在VM中
void getHeadData() {
        Subscription subscribe = App.getVP2Api().getArticlesHead(mId)
                .subscribeOn(Schedulers.io())
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {

                        // 逻辑代码修改
                        isLoading.set(false);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiDataSubscriber<ArticlesBean>() {

                    @Override
                    public void onSuccess(ArticlesBean headBean) {
                        if (headBean != null) {
                            setBean(headBean);
                        }
                    }

                    @Override
                    public void onFail(String errMsg) {

                    }


                });
        addSubscription(subscribe);
    }
  • XML 文件中绑定Data
<?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>
        <import type="com.vpgame.eric.utils.StringUtils" />
        <variable
            name="vm"
            type="com.vpgame.eric.main.articles.ArticlesDetailsVM" />
    </data>

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="248dp">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="248dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">

            <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="45dp">

                <ImageView
                    android:id="@+id/iv"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:scaleType="centerCrop"
                    app:imageUrl = "@{vm.bean.cover}"
                    app:placeHolder = "@{@drawable/default_holder}"
                    app:layout_collapseMode="parallax"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <ImageView
                    android:id="@+id/ov"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:background="#99000000"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="1.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintVertical_bias="1.0" />

                <TextView
                    android:id="@+id/tv_subc"
                    android:layout_width="wrap_content"
                    android:layout_height="17.39dp"
                    android:layout_marginRight="14.5dp"
                    android:layout_marginTop="8.7dp"
                    android:background="@drawable/bg_subc_articles_details"
                    android:gravity="center"
                    android:lines="1"
                    android:paddingLeft="11dp"
                    android:paddingRight="11dp"
                    android:text="@{vm.bean.subscriber.isSubscribed?@string/text_subscribed:@string/text_subscribe}"
                    android:selected="@{vm.bean.subscriber.isSubscribed}"
                    android:onClick="@{vm::onSubc}"
                    android:textColor="@{vm.bean.subscriber.isSubscribed?@color/color_3c3c3c:@color/white}"
                    android:textSize="9.86dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />


                <TextView
                    android:id="@+id/tv_subc_numb"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="8.7dp"
                    android:text="@{String.format(@string/format_subscriber,vm.bean.subscriber.count)}"
                    android:textColor="@color/color_a0a0a0"
                    android:textSize="9.86dp"
                    app:layout_constraintBottom_toBottomOf="@+id/tv_subc"
                    app:layout_constraintEnd_toStartOf="@+id/tv_subc"
                    app:layout_constraintTop_toTopOf="@+id/tv_subc" />


                <TextView
                    android:id="@+id/tv_title"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="35dp"
                    android:layout_marginStart="35dp"
                    android:layout_marginTop="61.45dp"
                    android:ellipsize="end"
                    android:gravity="center"
                    android:maxLines="2"
                    android:text="@{vm.bean.title}"
                    android:textColor="@color/white"
                    android:textSize="15.07dp"
                    android:textStyle="bold"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    tools:text="2017年基辅特级锦标赛" />

                <TextView
                    android:id="@+id/tv_desc"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="35dp"
                    android:layout_marginStart="35dp"
                    android:layout_marginTop="16dp"
                    android:ellipsize="end"
                    android:gravity="center"
                    android:maxLines="2"
                    android:text="@{vm.bean.subtitle}"
                    android:textColor="@color/white"
                    android:textSize="11.59dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/tv_title"
                    tools:text="八支队伍已获得基辅特锦赛的直接受邀资格,从北京时间
3月3日晚11时开始,在勇士令状里的互动指南版块" />


                <ImageView
                    android:id="@+id/iv_comment"
                    android:layout_width="11.6dp"
                    android:layout_height="11.6dp"
                    android:layout_marginBottom="14.5dp"
                    android:layout_marginLeft="14.5dp"
                    android:src="@mipmap/ic_msg_gray"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent" />


                <TextView
                    android:id="@+id/tv_comment_numb"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8.7dp"
                    android:text="@{StringUtils.formatNumber(vm.bean.comment_count)}"
                    android:textColor="@color/color_a0a0a0"
                    android:textSize="9.86dp"
                    app:layout_constraintBottom_toBottomOf="@+id/iv_comment"
                    app:layout_constraintStart_toEndOf="@+id/iv_comment"
                    app:layout_constraintTop_toTopOf="@+id/iv_comment"
                    />

                <ImageView
                    android:id="@+id/iv_read"
                    android:layout_width="11.6dp"
                    android:layout_height="11.6dp"
                    android:layout_marginLeft="17.39dp"
                    android:src="@mipmap/ic_read_gray"
                    app:layout_constraintBottom_toBottomOf="@+id/tv_comment_numb"
                    app:layout_constraintStart_toEndOf="@+id/tv_comment_numb"
                    app:layout_constraintTop_toTopOf="@+id/tv_comment_numb" />


                <TextView
                    android:id="@+id/tv_read_numb"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8.7dp"
                    android:text="@{StringUtils.formatNumber(vm.bean.pv)}"
                    android:textColor="@color/color_a0a0a0"
                    android:textSize="9.86dp"
                    app:layout_constraintBottom_toBottomOf="@+id/iv_read"
                    app:layout_constraintStart_toEndOf="@+id/iv_read"
                    app:layout_constraintTop_toTopOf="@+id/iv_read" />

            </android.support.constraint.ConstraintLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                app:contentInsetLeft="0dp"
                app:layout_collapseMode="pin"
                android:background="@color/colorPrimary"
                app:contentInsetStart="0dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <ImageButton
                        android:id="@+id/imbtn_tbar_back"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:background="@null"
                        android:paddingLeft="14.5dp"
                        android:paddingRight="14.5dp"
                        android:src="@mipmap/left_back"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />

                    <TextView
                        android:id="@+id/tv_tbar_title"
                        android:layout_width="0dp"
                        android:layout_height="0dp"
                        android:layout_marginLeft="60dp"
                        android:layout_marginRight="60dp"
                        android:ellipsize="end"
                        android:gravity="center"
                        android:lines="1"
                        android:text="@string/title_articles"
                        android:textColor="@color/white"
                        android:textSize="16dp"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />

                    <ImageButton
                        android:id="@+id/imbtn_tbar_share"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_marginRight="14.5dp"
                        android:background="@null"
                        android:onClick="@{vm::showShare}"
                        android:scaleType="centerCrop"
                        android:src="@mipmap/ic_share_photo"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />

                </android.support.constraint.ConstraintLayout>

            </android.support.v7.widget.Toolbar>


        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rv"
        app:layoutManager="LinearLayoutManager"
        app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">
    </android.support.v7.widget.RecyclerView>

    <FrameLayout
        android:id="@+id/fl_loading"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/color_f0f0f0"
        android:layout_marginTop="40dp"
        app:visibleGone="@{vm.isLoading}"
        >
        <ProgressBar
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_gravity="center"
            android:indeterminate="true"
            android:indeterminateDrawable="@anim/roate" />
    </FrameLayout>

</android.support.design.widget.CoordinatorLayout>
    </layout>
  • 以上即是使用MVVM DataBing解决问题的方案

猜你喜欢

转载自blog.csdn.net/JafarOne/article/details/80229773