我有4个复选框,我尝试在TextView上显示检查了多少个
我创建了一个变量numberOfTrue,我在switch中增加了它。
当然我的应用程序现在没有工作,textView仍显示“0”
更改单击框的数量后,变量不会刷新,我现在应该修复什么?
我不知道。
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int numberOfTrue = 0;
private TextView tv1;
private CheckBox cb1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox cb2,cb3,cb4;
Button b2;
b2 = (Button)findViewById(R.id.b2);
tv1 = (TextView)findViewById(R.id.tv1);
cb1 = (CheckBox)findViewById(R.id.cb1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.cb2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.cb3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.cb4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
tv1.setText(""+numberOfTrue);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
}
});
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cb1:
saveInSp("cb1",isChecked);
if (isChecked == true){
numberOfTrue++;
}
break;
case R.id.cb2:
saveInSp("cb2",isChecked);
if (isChecked == true){
numberOfTrue++;
}
break;
case R.id.cb3:
saveInSp("cb3",isChecked);
if (isChecked == true){
numberOfTrue++;
}
break;
case R.id.cb4:
saveInSp("cb4",isChecked);
if (isChecked == true){
numberOfTrue++;
}
break;
}
}
}
答案 0 :(得分:2)
1。)关注answer here,其中指的是TextView
使用字符串tv1.setText(""+numberOfTrue);
2。)在tv1.setText(""+numberOfTrue);
函数末尾添加onCheckedChanged(
以反映textview
事件后checkChange
中的新值
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// switch code
tv1.setText(""+numberOfTrue);
}