Short answer
You can use the ternary operator to make the visibility change simpler (instead of if
s).
I guess the approach here would be to count the number of checkboxes, then set the visibilities. You would just have to change your updateProgressBars()
method like this:
public void updateProgressBars() {
int nbCheckboxes = 0;
if (checkBox1.isChecked())
nbCheckboxes++;
if (checkBox2.isChecked())
nbCheckboxes++;
progressBar1.setVisibility(nbCheckboxes >= 1 ? View.VISIBLE : View.GONE);
progressBar2.setVisibility(nbCheckboxes >= 2 ? View.VISIBLE : View.GONE);
}
Other remarks
IF statement with boolean expressiosn
Your are using constructs such as:
if (myBooleanExpression == true)
The == true
is not needed because you're using a boolean expression here. Use instead:
if (myBooleanExpression)
Using arrays for your variables
If you use several numbered variables that have the same kind of purpose, you might want to consider using arrays.
public class Progress extends Activity {
ProgressBar[] progressBars;
CheckBox[] checkBoxes;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
SharedPreferences setprefsd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
setprefsd = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
progressBars = new ProgressBar[3]; // 3, or whatever number you have
progressBars[0] = (ProgressBar) findViewById(R.id.progressBar1);
progressBars[1] = (ProgressBar) findViewById(R.id.progressBar2);
progressBars[2] = (ProgressBar) findViewById(R.id.progressBar3);
checkBoxes = new CheckBox[3]; // 3 or whatever number you have
checkBoxes[0] = (CheckBox) findViewById(R.id.checkBox1);
checkBoxes[1] = (CheckBox) findViewById(R.id.checkBox2);
checkBoxes[2] = (CheckBox) findViewById(R.id.checkBox3);
checkBoxes[0].setChecked(setprefsd.getBoolean("FirstCheckBox", false));
checkBoxes[1].setChecked(setprefsd.getBoolean("SecondCheckBox", false));
checkBoxes[2].setChecked(setprefsd.getBoolean("ThirdCheckBox", false));
updateProgressBars();
}
public void updateProgressBars() {
int nbCheckBoxes = 0;
for (CheckBox cb : checkBoxes) {
if (cb.isChecked())
nbCheckBoxes++;
}
for (int i = 0; i < progressBars.length; i++) {
progressBars[i].setVisibility(nbCheckboxes > i ? View.VISIBLE : View.GONE);
}
}
}