Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How to add intervals texts in a seekbar

I am using a seekbar, and I want to add certain marks in the seekbar with text to use it as a scale. The selected interval points should be highlighted. enter image description here

The corresponding code is here:

   seekbar = (SeekBar) findViewById(R.id.seekBar1);
    seekbar.setMax(max);
    seekbar.setProgress(50);
    seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            // TODO Auto-generated method stub
            value.setText("SeekBar value is " + progress);
        }

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

        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
    });
like image 755
Sanghita Avatar asked Dec 10 '12 09:12

Sanghita


People also ask

What is SeekBar Setprogress?

↳ android.widget.SeekBar. A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. Placing focusable widgets to the left or right of a SeekBar is discouraged.


2 Answers

To make the above seek bar you first have to add a measuring scale as a background drawable. Then you'll have to make textboxes for each interval on the measuring scale.

<SeekBar 
        ....
android:progressDrawable="@drawable/progress"
android:thumb="@drawable/thumb"
        ....
/>

Then

public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {   
   progress = ((int)Math.round(progress/interval))*interval;
   seekBar.setProgress(progress);
   if(progress==5) textBox5.setTextColor(Color.RED);
   else if(progress==10) textBox10.setTextColor(Color.RED);
   //......... for all the text boxes.
}
like image 66
cjds Avatar answered Sep 21 '22 20:09

cjds


Actually, all The above solutions force to select the last progress point, which is not logic.

To make it mire accurete, Seek bar must detect which is the nearest dot and jump to it.

So below is the solution,

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

    int progressStep = getMax() / dotsCount;

    int lastDotProgress = Math.round(getProgress() / progressStep) * progressStep;
    int nextDotProgress = lastDotProgress + progressStep;
    int midBetweenDots = lastDotProgress + (progressStep / 2);

    if (getProgress() > midBetweenDots)
        seekBar.setProgress(nextDotProgress);
    else
        seekBar.setProgress(lastDotProgress);
}

You can use same behavior in onProgressChanged() if you want to prevent seeking between dots

like image 23
Simon K. Gerges Avatar answered Sep 22 '22 20:09

Simon K. Gerges