Android Seekbar float values from 0.0 to 2.0

kosma822 picture kosma822 · Mar 26, 2013 · Viewed 15.7k times · Source

how can I get the values ​​from 0.0 to 2.0 with a seekbar? values ​​should go in steps of 0.5 ( 0.0 , 0.5 , 1.0, 1.5, 2.0) can someone help me?

Answer

FoamyGuy picture FoamyGuy · Mar 26, 2013

SeekBar extends ProgressBar.

ProgressBar has a method

public void setMax(int max)

Since it only accepts int you'll have to do some conversion from an int value to get the float that you are after.

Something like this should do the trick:

mSeekBar.setMax(4);
//max = 4 so the possible values are 0,1,2,3,4
seekbar.setOnSeekBarChangeListener( new OnSeekBarChangeListener(){
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser)
    {
        // TODO Auto-generated method stub
        Toast.makeText(seekBar.getContext(), "Value: "+getConvertedValue(progress), Toast.LENGTH_SHORT).show();
    }
    public void onStartTrackingTouch(SeekBar seekBar)
    {
        // TODO Auto-generated method stub
    }
    public void onStopTrackingTouch(SeekBar seekBar)
    {
        // TODO Auto-generated method stub
    }
});

This part will be in your onCreate() and you'll have to use findViewById() or something to get a reference to mSeekBar.

public float getConvertedValue(int intVal){
    float floatVal = 0.0;
    floatVal = .5f * intVal;
    return floatVal;
}

This part is another method that you can add to your Activity that will convert from int to float values within the range you need.