Jetpack ViewModel 與 LiveData

介紹

  1. ViewModel :
    將UI中的數(shù)據(jù)模塊提出來單獨管理,使得控制器Activirty Fragment變得更加簡單,只需要專注界面,不需要管理界面復(fù)雜數(shù)據(jù), 且屏幕旋轉(zhuǎn)后數(shù)據(jù)不會丟失
  2. LiveData :
    為ViewModel 中的數(shù)據(jù)設(shè)置監(jiān)聽,數(shù)據(jù)改變時 自動刷新界面不需要以往的setText()

ViewModel 使用

加入依賴

implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'

創(chuàng)建ViewModel類繼承ViewModel

import androidx.lifecycle.ViewModel;

public class MyViewModle extends ViewModel {
    public int index = 0;
}

里面管理數(shù)據(jù)index

如果要使用Context,可以繼承AndroidViewModel

Java中使用

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);
    //省略 findViewById ......
    MyViewModle myViewModle = new ViewModelProvider(this).get(MyViewModle.class);
    // 屏幕翻轉(zhuǎn)后 進(jìn)入時先設(shè)置數(shù)據(jù) 省略onSaveInstanceState方法
    tv.setText(String.valueOf(myViewModle.index));
    // 點擊數(shù)據(jù)+1
    but.setOnClickListener(v -> {
        myViewModle.index++;
        tv.setText(String.valueOf(myViewModle.index));
    });
}

LiveData 使用

ViewModle中數(shù)據(jù)使用LiveData包裝

public class MyViewModle extends ViewModel {
    // public int index = 0;
    private MutableLiveData<Integer> liveDataIndex;

    //獲取liveDataIndex類型
    public MutableLiveData<Integer> getLiveDataIndex() {
        if (null == liveDataIndex) {
            liveDataIndex = new MutableLiveData<>();
            liveDataIndex.setValue(0);
        }
        return liveDataIndex;
    }

    //liveDataIndex 數(shù)據(jù)加1
    public void addLiveDataIndex() {
        getLiveDataIndex().setValue(liveDataIndex.getValue() + 1);
    }
}

Java中

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);
    //省略 findViewById ......
    MyViewModle myViewModle = new ViewModelProvider(this).get(MyViewModle.class);
    // 屏幕翻轉(zhuǎn)后 進(jìn)入時先設(shè)置數(shù)據(jù) 省略onSaveInstanceState方法
    tv.setText(String.valueOf(myViewModle.getLiveDataIndex().getValue()));
    // 獲取LiveData包裝的數(shù)據(jù)并設(shè)置監(jiān)聽, onChanged()方法會監(jiān)聽數(shù)據(jù)改變并更新界面
    myViewModle.getLiveDataIndex().observe(this, new Observer<Integer>() {
        @Override
        public void onChanged(Integer integer) {
            tv.setText(String.valueOf(integer));
        }
    });
    // 調(diào)用viewModle 中的方法更改數(shù)據(jù)后, 此時會調(diào)用上面的onChanged()方法
    but.setOnClickListener(v -> {
        myViewModle.addLiveDataIndex(1);
    });
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容