سؤال

I need a seekbar with value from 1 to 6 and step 0.5. So, values must are : 1 - 1.5 - 2 - 2.5 ...

What is the correct algorithm ?

هل كانت مفيدة؟

المحلول

I would store the possible values in an array and use the current seek-bar value as the element-index for accessing the "desired" value.

Like this

int[] values = {0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4};
int current = values[ seekbar.getValue() ];

نصائح أخرى

Define the seekbar in layout like this

        <SeekBar
        android:id="@+id/seekbar1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:progress="0"
        android:max="5"/>

And add this in your activity

public class MainActivity extends Activity {

 private SeekBar seekBar;
 private TextView textView;

 @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  seekBar = (SeekBar) findViewById(R.id.seekBar1);

  for(i=0;i<seekBar.getMax();i=i+0.5){
        Thread.sleep(500);
        seekBar.setProgress(i);
   }

 }

You could do this:

<SeekBar
    android:id="@+id/seek"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="12" />

and then access the seek bar with:

mSeekBar = (SeekBar) findViewById(R.id.seek);

    mSeekBar.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) {
            Toast.makeText(MainActivity.this, "" + (float) progress / 2, Toast.LENGTH_SHORT).show();
        }
    });

This will give you a toast with every change. You've just to divide each progress by 2.

EDIT 1: Or you can get the actual value with:

float value = (float) mSeekBar.getProgress() / 2;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top