成品鉴赏
思路
布局
MyViewModel 类,存放按钮触发功能
public class MyViewModel extends ViewModel {
private MutableLiveData<Integer> aTeamScore;
private MutableLiveData<Integer> bTeamScore;
private int aBack,bBack;
//A队伍的分数变化
public MutableLiveData<Integer> getaTeamScore(){
if(aTeamScore==null){
aTeamScore=new MutableLiveData<>();
aTeamScore.setValue(0);
}
return aTeamScore;
}
//B队伍的分数变化
public MutableLiveData<Integer> getbTeamScore(){
if(bTeamScore==null){
bTeamScore=new MutableLiveData<>();
bTeamScore.setValue(0);
}
return bTeamScore;
}
//A队伍添加分数
/*
aBack=aTeamScore.getValue();
bBack=bTeamScore.getValue();
记录新分数前记录本次分数,退回用到
*/
public void aTeamAdd(int p){
aBack=aTeamScore.getValue();
bBack=bTeamScore.getValue();
aTeamScore.setValue(aTeamScore.getValue()+p);
}
//B队伍添加分数
public void bTeamAdd(int p){
aBack=aTeamScore.getValue();
bBack=bTeamScore.getValue();
bTeamScore.setValue(bTeamScore.getValue()+p);
}
//重置
public void reset(){
aBack=aTeamScore.getValue();
bBack=bTeamScore.getValue();
aTeamScore.setValue(0);
bTeamScore.setValue(0);
}
//退回上一步
public void undo(){
aTeamScore.setValue(aBack);
bTeamScore.setValue(bBack);
}
}
public class MainActivity extends AppCompatActivity {
MyViewModel myViewModel;
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding= DataBindingUtil.setContentView(this,R.layout.activity_main);
myViewModel= ViewModelProviders.of(this).get(MyViewModel.class);
binding.setData(myViewModel);
binding.setLifecycleOwner(this);
}
}
页面