Android Jetpack 之使用 ViewModel
ViewModel 是 Jetpack MVVM 架構中的 VM 部分。ViewModel 中的資料不會因為 Activity 重建而被銷毀。
以下的 ViewModel 儲存了開始時間戳。
public class ChronometerViewModel extends ViewModel {
@Nullable
private Long mStartTime;
@Nullable
public Long getStartTime() {
return mStartTime;
}
public void setStartTime(final long startTime) {
this.mStartTime = startTime;
}
}
在 ChronoActivity2 使用 chronometer 計時器顯示倒計時。當螢幕旋轉時,Activity 重走 onCreate。但是 chronometerViewModel 的 startTime 依然存在,旋轉後會繼續之前的倒計時。
public class ChronoActivity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The ViewModelStore provides a new ViewModel or one previously created.
ChronometerViewModel chronometerViewModel
= new ViewModelProvider(this).get(ChronometerViewModel.class);
// Get the chronometer reference
Chronometer chronometer = findViewById(R.id.chronometer);
if (chronometerViewModel.getStartTime() == null) {
// If the start date is not defined, it's a new ViewModel so set it.
long startTime = SystemClock.elapsedRealtime();
chronometerViewModel.setStartTime(startTime);
chronometer.setBase(startTime);
} else {
// Otherwise the ViewModel has been retained, set the chronometer's base to the original
// starting time.
chronometer.setBase(chronometerViewModel.getStartTime());
}
chronometer.start();
}
}