javaandroidseekbar

How to set seekbar min and max value


I have a seekbar and trying to set the value from 60 to 180 for one and 40 to 190 for the second one in step of 1.

sb1 = (SeekBar) findViewById(R.id.progresss);
        sb1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

            @Override       
            public void onStopTrackingTouch(SeekBar seekBar) {      
                // TODO Auto-generated method stub
                //int inVal = Integer.parseInt(String.valueOf(seekBar.getProgress()));
                //inVal =+ 70;
                //Toast.makeText(getApplicationContext(), String.valueOf(inVal),Toast.LENGTH_LONG).show();
            }       

            @Override       
            public void onStartTrackingTouch(SeekBar seekBar) {     
                // TODO Auto-generated method stub      
            }       

            @Override       
            public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
                // TODO Auto-generated method stub
                progress =+ 70;
                Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();

            }       
        });

is not working. Any idea how to fix it?


Solution

  • You cannot set the min value of a SeekBar (always 0) and you cannot set the step value of a SeekBar (always 1).

    To set the value from 60 to 180 with a step of 1:

    int step = 1;
    int max = 180;
    int min = 60;
    
    // Ex : 
    // If you want values from 3 to 5 with a step of 0.1 (3, 3.1, 3.2, ..., 5)
    // this means that you have 21 possible values in the seekbar.
    // So the range of the seek bar will be [0 ; (5-3)/0.1 = 20].
    seekbar.setMax( (max - min) / step );
    
    
    seekbar.setOnSeekBarChangeListener(
        new OnSeekBarChangeListener()
        {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
    
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
    
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, 
                boolean fromUser) 
            {
                // Ex :
                // And finally when you want to retrieve the value in the range you
                // wanted in the first place -> [3-5]
                //
                // if progress = 13 -> value = 3 + (13 * 0.1) = 4.3
                double value = min + (progress * step);
    
            }
        }
    );
    

    I put another example within the code so that you understand the math.