How to set seekbar min and max value

前端 未结 14 896
栀梦
栀梦 2020-11-28 09:17

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.progress         


        
14条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 09:53

    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.

提交回复
热议问题