LiveData | Android Jetpack
LiveData組件:在底層數據更改時自動通知視圖
通常LiveData會和ViewModel一起使用來實現MVVM架構,當然LiveData也可以單獨使用。以下是LiveData和ViewModel一起使用的簡單範例。
步驟:
效果圖
ViewModel (MainViewModel)
public class MainViewModel extends ViewModel {
private MutableLiveData<Integer> count;
public MutableLiveData<Integer> getCount() {
// 如果數據為空, 就初始化一個LiveData型別的容器, 並設定初始值
if (count == null) {
count = new MutableLiveData<>();
count.setValue(0);
}
return count;
}
public void addCount() {
count.setValue(count.getValue() + 1);
}
public void subCount() {
count.setValue(count.getValue() - 1);
}
}
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private MyViewModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 獲取ViewModel
model = new ViewModelProvider(this).get(MyViewModel.class);
// 點擊'-'按鈕對model的count+1
binding.btnAdd.setOnClickListener( view -> model.addCount() );
// 點擊'-'按鈕對model的count-1
binding.btnSub.setOnClickListener( view -> model.subCount() );
// 當我們的數據發生改變的時候就會呼叫onChanged()函數
model.getCount().observe(this, integer -> {
binding.textCount.setText(String.valueOf(integer));
});
}
}