Question

I have a simple slider (SeekBar) with the fixed range [0, 8]

When I change the value of this slider I want to convert these values as follows

[0, 0.25, 0.5, 1, 2, 4, 8, 16, 32]

It's late and I've confused myself with the maths - what's the simplest way to do this? I convinced myself there should be a simple way to do it using powers ( Math.pow() ) but failed a number of times

edit Just thought I'd add - I know how to get the progress updates using an OnSeekBarChangeListener it's just the actual conversion algorithm I'm struggling with

Was it helpful?

Solution

The simplest way to accomplish it is to reference an array you have assigned somewhere in your code (as comments/other users have pointed out):

// somewhere in your code (possibly static?)
double[] _result = { 0, 0.25, 0.5, 1, 2, 4, 8, 16, 32 };

// then your function
public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser)
{
    // would need to handle if progress is ever > _result.max
    System.out.format("%f%n", _result[progress]);
}

However, if you want the mathematical way to do it (based on the inputs/outputs you've specified), you'll need to implement some bit shifting:

public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser)
{
    // get the 'max' of our bar
    double max = (double)seekBar.getMax(); // 8
    // get the 'max' of our 'array' values, this could be a const value
    // or some other formula (like max * 4f)
    double pmax = 32;
    // get our 'mask' by shifting '1' left 'progress' times, then divide by 2
    // to get the divisor to our other formula
    double p = (double)(1 << progress) / 2; 
    // if progress == 0, then just return 0 (since that's our min)
    double val = ((progress == 0) ? 0 : (max / (pmax / p)));

    // the 'one-liner': 
    // ((double)seekBar.getMax()) / (pmax / ((double)(1 << progress) / 2)))

    System.out.format("%f%n", val);
}

Hope that can help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top