gian848396 gian848396 - 4 months ago 14
Android Question

How to setText to total of all SeekBar progress values?

I want "result.setText" to show the changing total of the accumulative progress of all of the SeekBars. I'm also trying to store that changing int to a variable of its own(equal to the total of all of the SeekBar's progress.)

I have 9 SeekBars, all of them have a max of 3. When I change any one of them up I want totalScoreInt to equal +1. If I were to move each SeekBar up one from 0, one at a time, I would want TotalScoreInt to grow by 1, from 0 to 27 and the TotalScoreInt would shrink by 1 from 27 to 0 if I were to do the opposite from each at their max.

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

seekBar1value = progress;
seekBar2value = progress;
seekBar3value = progress;
seekBar4value = progress;
seekBar5value = progress;
seekBar6value = progress;
seekBar7value = progress;
seekBar8value = progress;
seekBar9value = progress;

totalScoreInt =
(seekBar1value
+ seekBar2value
+ seekBar3value
+ seekBar4value
+ seekBar5value
+ seekBar6value
+ seekBar7value
+ seekBar8value
+ seekBar9value);

switch (seekBar.getId()){
case R.id.seekBar1:
result.setText("Score: " +progress);
break;

case R.id.seekBar2:
result.setText("Score: " +progress);
break;

case R.id.seekBar3:
result.setText("Score: " +progress);
break;

case R.id.seekBar4:
result.setText("Score: " +progress);
break;

case R.id.seekBar5:
result.setText("Score: " +progress);
break;

case R.id.seekBar6:
result.setText("Score: " +progress);
break;

case R.id.seekBar7:
result.setText("Score: " +progress);
break;

case R.id.seekBar8:
result.setText("Score: " +progress);
break;

case R.id.seekBar9:
result.setText("Score: " +progress);
break;
}

//result.setText(String.valueOf("Score: " +totalScoreInt));
}


This code sets the text to whatever the last changed SeekBar progress value was at.

I want that number to grow or shrink each time change any of the SeekBars progress.

So if seekBar1 progress = 3 and seekBar2 progress = 2 totalScoreInt would equal 5 and that would be set in "result"

Answer

You have to keep a global reference for each and every SeekBar, alongside with your counter variable. Then, create a method somewhat like this:

private int progress;

private SeekBar sb1, sb2, sb3; // And the others...

private synchronized void handleSeekBars() {
    progress = sb1.getProgress() + sb2.getProgress() + sb3.getProgress();
}

And then, call it inside each SeekBar#OnSeekBarChangeListener(), like this:

sb1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        handleSeekBars();
        result.setText("Score: " + progress);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) { }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) { }
});

That should do the trick.

Comments