How to set seekbar min and max value
Asked Answered
F

15

52

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?

Forgiving answered 24/12, 2013 at 13:41 Comment(3)
Check thisVisby
try thisLuca
The min value is always 0. You cannot change it.Monjo
R
121

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.

Rhnegative answered 4/8, 2014 at 12:19 Comment(5)
Nothing is ever too late and thank you for posting your solution. I understand it better now :)Forgiving
This should be the accepted answer. Way more easier to understand !Vernalize
very nice solutionPhenylketonuria
this is the best answerGiuliana
I call it a programmatic way to solve an problem. Excellent solution.Trabzon
Y
41

You can set max value for your seekbar by using this code:

    sb1.setMax(100);

This will set the max value for your seekbar.

But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.

For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.

You can get more info via this link.

Yentai answered 24/12, 2013 at 13:51 Comment(4)
perfect. This should be on topThaw
This is the best answer for this questionTrammel
Although this answer is true for Max value but it does not answer the question as it says Min and Max so no upvote until a comprehensive solution is provided!Anticlastic
Starting from API Level 26 you can use it like this sb1.setMin(40)Fuliginous
C
15
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) {

                int MIN = 5;
                if (progress < MIN) {

                    value.setText(" Time Interval (" + seektime + " sec)");
                } else {
                    seektime = progress;
                }
                value.setText(" Time Interval (" + seektime + " sec)");

            }
        });
Condon answered 24/12, 2013 at 13:46 Comment(3)
Thanks. I went with a NumberPicker with prefilled numbers.Forgiving
Hey, why does Android Studio say that the methods don't override method from its superclass?Footrope
I want to set -180 to 180 value in Seekbar. it's working well in android above 5 versions of the android device but in below It's doesn't show me the negative value in the Seekbar.Basidium
O
11

The easiest way to set a min and max value to a seekbar for me: if you want values min=60 to max=180, this is equal to min=0 max=120. So in your seekbar xml set property:

android:max="120"

min will be always 0.

Now you only need to do what your are doing, add the amount to get your translated value in any change, in this case +60.

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int translatedProgress = progress + 60;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

Be careful with the seekbar property android:progress, if you change the range you must recalculate your initial progress. If you want 50%, max/2, in my example 120/2 = 60;

Overland answered 26/7, 2016 at 12:24 Comment(0)
M
4

Seek Bar has methods for setting max values but not for setting min value here i write a code for setting minimum seek bar value when we add this code then your seek bar values not less then mim value try this its work fine for me

          /*   This methods call after seek bar value change */           

            public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            /* Check the current seekbar value is greather than min value*/
            if (progress < MIN_VALUE) {
                /* if seek bar value is lesser than min value then set min value to seek bar */
                seekBar.setProgress(MIN_VALUE);
            }

        }
Mckenna answered 8/5, 2014 at 7:1 Comment(1)
Please explain what this code does. Just don't leave the code alone.Query
S
2

If you are using the AndroidX libraries (import androidx.preference.*), this functionality exists without any hacky workarounds!

    val seekbar = findPreference("your_seekbar") as SeekBarPreference
    seekbar.min = 1
    seekbar.max = 10
    seekbar.seekBarIncrement = 1
Sheldon answered 22/12, 2018 at 1:1 Comment(0)
O
2

For requirements like this I have created Utility to customize Seekbar progress like below code:

SeekBarUtil.class

   import android.widget.SeekBar;
import android.widget.TextView;

public class SeekBarUtil {

    public static void setSeekBar(SeekBar mSeekbar, int minVal, int maxVal, int intervalVal, final TextView mTextView, String startPrefix, String endSuffix) {

        int totalCount = (maxVal - minVal) / intervalVal;
        mSeekbar.setMax(totalCount);
        mSeekbar.setOnSeekBarChangeListener(new CustomSeekBarListener(minVal, maxVal, intervalVal) {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //progress = ((int)Math.round(progress/interval))*interval;
                int val = min;
                if (interval == totalCount) {
                    val = max;
                } else {
                    val = min + (progress * interval);
                }
                seekBar.setProgress(progress);
                mTextView.setText(startPrefix + val + endSuffix);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {  }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {   }
        });

    }
}

and CustomSeekBarListener.class

import android.widget.SeekBar;

class CustomSeekBarListener implements SeekBar.OnSeekBarChangeListener {
    int min=0,max=0,interval=1;
    int totalCount;
    public CustomSeekBarListener(int min, int max, int interval) {
        this.min = min;
        this.max = max;
        this.interval = interval;
        totalCount= (max - min) / interval;
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) { }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) { }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) { }
}

and you can use it like below code snippet

SeekBarUtil.setSeekBar(seekbarAmountNeeded,10000,200000,5000,textAmount,"$"," PA");
Ogburn answered 9/1, 2019 at 12:17 Comment(0)
R
1

Another solution to handle this case is creating a customized Seekbar, to get ride of converting the real value and SeekBar progress every time:

import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar

//
// Require SeekBar with range [Min, Max] and INCREMENT value,
// However, Android Seekbar starts from 0 and increment is 1 by default, Android supports min attr on API 26,
// To make a increment & range Seekbar, we can do the following conversion:
//
//     seekbar.setMax((Max - Min) / Increment)
//     seekbar.setProgress((actualValue - Min) / Increment)
//     seekbar.getProgress = Min + (progress * Increment)
//
// The RangeSeekBar is responsible for handling all these logic inside the class.

data class Range(val min: Int, val max: Int, private val defaultIncrement: Int) {
    val increment = if ((max - min) < defaultIncrement) 1 else defaultIncrement
}


internal fun Range.toSeekbarMaximum(): Int = (max - min) / increment


class RangeSeekBar: SeekBar, SeekBar.OnSeekBarChangeListener {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    var range: Range = Range(0, 100, 1)
        set(value) {
            field = value
            max = value.toSeekbarMaximum()
        }

    var value: Int = 0
        get() = range.min + progress * range.increment
        set(value) {
            progress = (value - range.min) / range.increment
            field = value
        }

    var onSeekBarChangeListenerDelegate: OnSeekBarChangeListener? = this

    override fun setOnSeekBarChangeListener(l: OnSeekBarChangeListener?) {
        onSeekBarChangeListenerDelegate = l
        super.setOnSeekBarChangeListener(this)
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        onSeekBarChangeListenerDelegate?.onProgressChanged(seekBar, value, fromUser)
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
        onSeekBarChangeListenerDelegate?.onStartTrackingTouch(seekBar)
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
        onSeekBarChangeListenerDelegate?.onStopTrackingTouch(seekBar)
    }
}

Then in your fragment,

    // init
    range_seekbar.range = Range(10, 110, 10)
    range_seekbar.value = 20

    // observe value changes
    range_seekbar.userChanges().skipInitialValue().subscribe {
        println("current value=$it")
    }

Keywords: Kotlin, range SeekBar, Rx

Rosen answered 16/9, 2018 at 3:30 Comment(0)
D
1

You can use Material design sliders instead of seekbar

<com.google.android.material.slider.Slider
    ...
    android:valueFrom="60"
    android:valueTo="180"
    android:stepSize="10.0"  />'

for more check here https://material.io/components/sliders/android

Doe answered 19/2, 2021 at 11:28 Comment(0)
B
0

Set seekbar max and min value

seekbar have method that setmax(int position) and setProgress(int position)

thanks

Bituminous answered 24/12, 2013 at 13:45 Comment(0)
B
0

Copy this class and use custom Seek Bar :

public class MinMaxSeekBar extends SeekBar implements SeekBar.OnSeekBarChangeListener {
private OnMinMaxSeekBarChangeListener onMinMaxSeekBarChangeListener = null;
private int intMaxValue = 100;
private int intPrgress = 0;
private int minPrgress = 0;


public int getIntMaxValue() {
    return intMaxValue;
}

public void setIntMaxValue(int intMaxValue) {
    this.intMaxValue = intMaxValue;
    int middle = getMiddle(intMaxValue, minPrgress);
    super.setMax(middle);
}

public int getIntPrgress() {
    return intPrgress;
}

public void setIntPrgress(int intPrgress) {
    this.intPrgress = intPrgress;
}

public int getMinPrgress() {
    return minPrgress;
}

public void setMinPrgress(int minPrgress) {
    this.minPrgress = minPrgress;
    int middle = getMiddle(intMaxValue, minPrgress);
    super.setMax(middle);
}

private int getMiddle(int floatMaxValue, int minPrgress) {
    int v = floatMaxValue - minPrgress;
    return v;
}

public MinMaxSeekBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setOnSeekBarChangeListener(this);
}

public MinMaxSeekBar(Context context) {
    super(context);
    this.setOnSeekBarChangeListener(this);
}

@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
    intPrgress = minPrgress + i;
    onMinMaxSeekBarChangeListener.onMinMaxSeekProgressChanged(seekBar, intPrgress, b);
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    onMinMaxSeekBarChangeListener.onStartTrackingTouch(seekBar);

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    onMinMaxSeekBarChangeListener.onStopTrackingTouch(seekBar);
}

public static interface OnMinMaxSeekBarChangeListener {
    public void onMinMaxSeekProgressChanged(SeekBar seekBar, int i, boolean b);

    public void onStartTrackingTouch(SeekBar seekBar);

    public void onStopTrackingTouch(SeekBar seekBar);
}

public void setOnIntegerSeekBarChangeListener(OnMinMaxSeekBarChangeListener floatListener) {
    this.onMinMaxSeekBarChangeListener = floatListener;
}
}

This class contains method public void setMin(int minPrgress) for setting minimum value of Seek Bar This class contains method public void setMax(int maxPrgress) for setting maximum value of Seek Bar

Burmeister answered 23/3, 2015 at 11:31 Comment(1)
I could not make this work - your seek bar draws seek indicator in wrong placeMagdalen
O
0

Min-value will always start at zero and its nothing you can do about it. But you can change its value when user start scrolling it around.

Here I set the max-value as 64. This calculations are simple: I want the user to pick a time from 15min to 16 hours, and he picks one of every 15min to 16 hours, clear? I know, very simple :)

    SeekBar seekBar = (SeekBar) dialog.findViewById(R.id.seekBar);
    seekBar.setMax(64);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        float b;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            float des = (float) progress / 4;
            b = des;
            hours.setText(des + " hours");
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {


        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            hoursSelected = b;
        }
    });
Oared answered 8/12, 2015 at 22:48 Comment(0)
A
0
    private static final int MIN_METERS = 100;
    private static final int JUMP_BY = 50;

    metersText.setText(meters+"");
    metersBar.setProgress((meters-MIN_METERS));
    metersBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
            progress = progress + MIN_METERS;
            progress = progress / JUMP_BY;
            progress = progress * JUMP_BY;
            metersText.setText((progress)+"");
        }
    });
}
Achromic answered 19/2, 2018 at 7:13 Comment(0)
S
0
    paySeekRange.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            Debug.i(TAG, "onProgressChanged 1: " + progress);
            int progressMin = (progress * (maxPayRange - minPayRange) / 100) + minPayRange;
            Debug.i(TAG, "onProgressChanged 2: " + progress);
            int progressMax = (progress * (maxPayRange) / 100);
            progress = (progress * (progressMax - progressMin) / 100) + progressMin;
            Debug.i(TAG, "onProgressChanged 3: " + progress);
            txtWeeklyPay.setText("$".concat(String.valueOf(progress)));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
Selfmastery answered 22/12, 2018 at 6:10 Comment(1)
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Flopeared
S
-2

There is no option to set a min or max value in seekbar , so you can use a formula here to scale your value.

Desired_value = ( progress * ( Max_value - Min_value) / 100 ) + Min_value

I have tested this formula in many examples. In your example, if the progressBar is the middle(i.e. progress = 50 ) and your Min_val and Max_val are 60 and 180 respectively, then this formula will give you the Desired_value '120'.

Sannyasi answered 16/8, 2017 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.