我想看看你选择的样式。
观察活动/小部件中的数据,并对更改做出响应。
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:1.1.1"
下面是一个使用类似观察者的模式显示ViewModel和活动的示例:
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.View;
//Extend FRAGMENT ACTIVITY
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get handle on the ViewModel:
final ViewModelMain viewModelMain = ViewModelProviders.of(this).get(ViewModelMain.class);
//Observe the data in the viewmodel class:
viewModelMain.homeWickets.observe(this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer integer) {
//MAKE CHANGES WHEN THE VALUE FOR THE HOME WICKETS CHANGE LIKE SET ON CLICK METHODS TO NULL?
}
});
viewModelMain.homeScore.observe(this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer integer) {
//MAKE CHANGES WHEN THE VALUE FOR THE HOME SCORE CHANGE LIKE SET ON CLICK METHODS TO NULL?
}
});
//HOW TO SET A VIEW MODEL VALUE LIKE AFTER CLICKING A BUTTON:
View v = new View(getApplicationContext());
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModelMain.setHomeScore(viewModelMain.getHomeScore().getValue() + 1);
}
});
}
}
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
public class ViewModelMain extends AndroidViewModel {
public ViewModelMain(@NonNull Application application) {
super(application);
// Set all values to 0 when constructed?
this.awayScore.postValue(0);
this.homeScore.postValue(0);
this.homeWickets.postValue(0);
this.awayWickets.postValue(0);
}
public MutableLiveData<Integer> awayScore = new MutableLiveData<>();
public MutableLiveData<Integer> homeScore = new MutableLiveData<>();
public MutableLiveData<Integer> homeWickets = new MutableLiveData<>();
public MutableLiveData<Integer> awayWickets = new MutableLiveData<>();
//SETTERS -> POST THE DATA TO THE MUTABLE FIELDS
public void setAwayScore(Integer awayScore) {
this.awayScore.postValue(awayScore);
}
public void setAwayWickets(Integer awayWickets) {
this.awayWickets.postValue(awayWickets);
}
public void setHomeScore(Integer homeScore) {
this.homeScore.postValue(homeScore);
}
public void setHomeWickets(Integer homeWickets) {
this.homeWickets.postValue(homeWickets);
}
//STANDARD JAVA GETTERS
public MutableLiveData<Integer> getAwayScore() {
return awayScore;
}
public MutableLiveData<Integer> getAwayWickets() {
return awayWickets;
}
public MutableLiveData<Integer> getHomeScore() {
return homeScore;
}
public MutableLiveData<Integer> getHomeWickets() {
return homeWickets;
}
}