Android MVVM再升级 DataBinding+Retrofit+RxJava+ViewModel+LiveData(三)

本文主要使用泛型优化项目结构,只对关键修改部分进行说明,如果不了解项目结构请看我的上两篇博客:

Android MVVM改进版 DataBinding+Retrofit+RxJava+ViewModel+LiveData(二)

Android MVVM基础版 DataBinding+Retrofit+RxJava(一)

一、修改BaseActivity 

public abstract class BaseActivity extends AppCompatActivity {
    private String TAG = "";
    protected boolean isActive;
    private WaitingAlertDialog waitDialog;

    protected VM viewModel;
    protected DB dataBinding;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this,getLayoutId());

        Class viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            viewModel = ViewModelProviders.of(this).get(viewModelClass);
        }
        initViews(savedInstanceState);
    }

    public abstract int getLayoutId();

    /**
     * 初始化views
     *
     * @param savedInstanceState
     */
    public abstract void initViews(Bundle savedInstanceState);


}

添加两个泛型, VM和DB 分别继承AndroidViewModel和ViewDataBinding,添加getLayoutId()方法获取布局id,initViews(Bundle savedInstanceState)方法一般在这里进行一些初始化布局操作

二、修改MainActivity

public class MainActivity extends BaseActivity {
    private LinearLayoutManager layoutManager;
    private MainAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initViews(Bundle savedInstanceState) {
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        dataBinding.recyclerView.setLayoutManager(layoutManager);
        adapter = new MainAdapter(this);
        dataBinding.recyclerView.setAdapter(adapter);
        showWaitDialog();//显示加载动画
        viewModel.getList().observe(this, new Observer>>() {
            @Override
            public void onChanged(@Nullable BaseBean> listBaseBean) {
                if (listBaseBean.getErrorCode() == 0) {
                    dismissWaitDialog();//关闭加载图
                    adapter.setData(listBaseBean.getData());
                }

            }
        });
    }

}

MainActivity集成BaseActivity传入自己ViewModel和DataBInding,然后可以直接使用它们的对象。

三、总结

写的东西很简单,大神可以直接看我的第一篇博客开头写的几个链接的github项目都比较好

你可能感兴趣的:(Android)