ViewModel+LiveData最新版1.1.1的实现案例及fragment懒加载

备注:viewmodel+livedata 在1.1.0之后改动较大,ViewModelProvides类抛弃了,需要使用新的方法获取,后面有提到

最新版为1.1.1,

// alternatively, just ViewModel
implementation "android.arch.lifecycle:viewmodel:1.1.1"
//just LiveData
implementation "android.arch.lifecycle:livedata:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
//需要使用 java8 特性的 使用这个依赖
// implementation "android.arch.lifecycle:common-java8:1.1.1"

//Lazyfragmen懒加载Fragment的基类,仅仅在用户可见时调用loaddata
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;


/**
* A simple { @link Fragment} subclass.
*/
public abstract class BaseFragment extends Fragment {

boolean isUiVisible;
boolean isViewCreate;

public BaseFragment() {
// Required empty public constructor
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isViewCreate = true;
lazyLoad();
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isUiVisible = isVisibleToUser;
lazyLoad();
}

protected void lazyLoad(){
if (isUiVisible && isViewCreate){
loadData();
}
}

public abstract void loadData();
}

//ViewModel和LiveData 模拟异步请求获取model
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import java.util.ArrayList;
import java.util.List;

/**
* @author XiongJiaLong
* @ClassName MyUserModel
* @date 2018 04 25 10:32
*/

//自定义的ViewModel,在此类中执行异步任务获取model

public class MyUserModel extends ViewModel {
MutableLiveData> mutableLiveData;

Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {

            //该方法必须要在主线程执行,否则报错

mutableLiveData.setValue(l);
}
};
List l;
public LiveData> getUserModel(){
if (mutableLiveData == null){
mutableLiveData = new MutableLiveData<>();
loadData();
}
return mutableLiveData;
}

void loadData(){
new ThreadCall().start();
}

public void setNewData(User user){
mutableLiveData.getValue().set(0,user);
}


class ThreadCall extends Thread{

@Override
public void run() {
try {
Thread. sleep (2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
l = new ArrayList<>();
for (int i=0;i<10;i++){
l.add(new User(i+" 姓名 ",20+i,150+i));
}
handler.sendEmptyMessage(0);
}
}
}

// MainActivity获取自定义 viewmodel
void initData(){
//使用new的形式获取model 不存在
// viewModelProvider = new ViewModelProvider(this,
// ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()));
// myUserModel = viewModelProvider.get(MyUserModel.class);

// viewmodel 1.1.0之后正确获取 ViewModel 的姿势 viewModelProvider=ViewModelProvider.AndroidViewModelFactory. getInstance (getApplication());
myUserModel = viewModelProvider.create(MyUserModel.class);
}
//给 fragment用来获取viewmodel 将myUserModel 设置为静态的也可以,根据使用范围设置
public MyUserModel getMyUserModel() {
return myUserModel;
}

////懒加载 fragment 的实现及 ViewModel 的调用
public class BlankFragment extends BaseFragment implements View.OnClickListener, Observer> {

String tit;
TextView tv;
Button btn;
MyUserModel userModel;

public static BlankFragment getFragment(String s){
BlankFragment f = new BlankFragment();
Bundle b = new Bundle();
b.putString("content",s);
f.setArguments(b);
return f;
}

public BlankFragment() {
// Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tit = getArguments().getString("content");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater,container,savedInstanceState);
View inflate = inflater.inflate(R.layout. fragment_blank , container, false);
tv = inflate.findViewById(R.id. neiRong );
btn = inflate.findViewById(R.id. change_btn );
btn.setOnClickListener(this);
// 拿到ViewModel 并且设置 data的变化监听,
userModel = MainActivity. myUserModel ;
userModel.getUserModel().observe(getActivity(),this);
return inflate;
}

@Override
public void loadData() {
getData();
}

void getData(){
if (userModel!=null) {
List value = userModel.getUserModel().getValue();
if (value != null) {
tv.setText(value.get(0).toString());
}
}
}

@Override
public void onClick(View view) {
User user = new User();
user.setAge(100);
user.setHeight(100);
user.setName(this.getClass().getName());
if (userModel!=null)
//改变单个值不会触发 onChanged 方法
userModel.setNewData(user);
}

// 此监听只会在 setValue的时候调用,如果只改变单个的值不调用改方法,但是重新获取值会改变
@Override
public void onChanged(@Nullable List users) {
Log. e ("====BlandFragment====","=====onChanged======");
List value = userModel.getUserModel().getValue();
tv.setText(value.get(value.size()-1).toString());
}
}

//懒加载fragment
public class TestFragment1 extends BaseFragment implements View.OnClickListener {


TextView t;
MyUserModel userModel;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout. fragment_test_fragment1 , container, false);
t = view.findViewById(R.id. tv_received );
t.setOnClickListener(this);
return view;
}

@Override
public void loadData() {
getData();
}

void getData(){
userModel = MainActivity. myUserModel ;
t.setText(userModel.getUserModel().getValue().get(0).toString());
}

@Override
public void onResume() {
super.onResume();
}

@Override
public void onPause() {
super.onPause();
}

@Override
public void onClick(View view) {
User user = new User();
user.setAge(500);
user.setHeight(500);
user.setName(this.getClass().getName());
List list = new ArrayList<>();
list.add(user);
if (userModel!=null)
//此设置会出发 onChanged 方法回调
userModel.mutableLiveData.setValue(list);
}
}

你可能感兴趣的:(android布局,android工具类,android第三方库,android框架)