Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Set interval in SeekBar

Tags:

android

In my application I have a Seekbar that is shown in a dialog. Now I wanna set the interval and step in the Seekbar. The interval should be 0-250 and each step should be 5 minutes.

so far this is my code:

public class seekActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
    SeekBar seekbar;
    Button button;
    TextView textview;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //set up main content view
        setContentView(R.layout.main);
        //this button will show the dialog
        Button button1main = (Button) findViewById(R.id.Button01main);
        button1main.setOnClickListener(this);
    }
    public void onClick(View v) {
        //set up dialog
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.maindialog);
        dialog.setTitle("This is my custom dialog box");
        dialog.setCancelable(true);
        button = (Button) dialog.findViewById(R.id.Button01);
        seekbar = (SeekBar) dialog.findViewById(R.id.seekBar1);
        seekbar.setOnSeekBarChangeListener(this);
        textview = (TextView) dialog.findViewById(R.id.textView1);
        dialog.show();
    }
    public class SeekBarPreference {
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {
        // TODO Auto-generated method stub
        textview.setText(progress + "");
    }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    };
}

Could anyone give me some tips/code how to do?

Thanks!

like image 925
Seb Avatar asked Jun 21 '11 20:06

Seb


3 Answers

You have to just update the onProgressChanged method as follows.


int stepSize = 5;
public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
    progress = ((int)Math.round(progress/stepSize))*stepSize;
    seekBar.setProgress(progress);
    textview.setText(progress + "");

}
like image 161
gypsicoder Avatar answered Oct 20 '22 16:10

gypsicoder


Instead of doing this why not just set the max value of the SeekBar to 50 (250/5) and then do whatever conversion is necessary from the SeekBar values to "real" values?

like image 24
cyngus Avatar answered Oct 20 '22 17:10

cyngus


If you use

Math.round((float)progress / stepSize) * stepSize

your threshold will be in the middle of two steps

If you use

progress / stepSize * stepSize

the slider will always jump to the left step. This will just cut the decimals in the division.

like image 2
Rene B. Avatar answered Oct 20 '22 18:10

Rene B.