09 May 2014

Setting up the SeekBar

So we want to use the SeekBar. We want the minimum value to be 10 and the maximum value to be 100, and it should increment by 10.

Thing is, SeekBar by default always starts at 0, and the increment is always an int. It is definitely possible to get what we want, but we need to do some simple math first.

Compute how many increments you will need from your minimum up to your maximum:
numberOfIncrements = maximum - minimum = 90

Then divide it by the amount of each increment we want:
seekBarMaximum = numberOfIncrements / 10 = 9

This means we should set up the SeekBar to have max = 9 and increment = 1. Then in our code, we have to figure out how to get the actual progress that we want.
SeekBar.OnSeekBarChangeListener mSeekbarListener = new OnSeekBarChangeListener() {
			
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) { /* Do nothing*/ }
			
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) { /* Do nothing*/ }
			
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		mProgressDisplay.setText("Seekbar is at: " + getProgressToDisplay(progress));
	}
};


private String getProgressToDisplay(int progress) {
        // We are multiplying by 10 since it is our actual increment
	int actualProgress = (progress + 1) * 10;
	return String.valueOf(actualProgress);
}

Another example:
minimum = 1, maximum = 10, increment = 0.5
numberOfIncrements = 9
seekBarMaximum = 18

In this case, the contents of getProgressToDisplay() will change since the increment is not a whole number.
private String getProgressToDisplay(int progress) {
	float actualProgress = (progress + 1) - (progress * 0.5f);
	return String.valueOf(actualProgress);
}