SpiralDev
SpiralDev

Reputation: 7331

Slider to choose numbers between -24 and 24 with 0.5 step

I want to create slider that gives to the user an ability to choose numbers on a range of -24 to 24 with 0.5 steps. So that, I decided to create slider whose thumb is located at the center and could be slided to both left and right sides. Here's the picture of what I am aiming at: thumb is located at the center and user can move it to both sides

When user moves the thumb of slider to the left it sets negative numbers. Similarly, when user moves it to the right it sets positive numbers.

How can I achieve this? Is there another better way to give a user such ability?

Upvotes: 1

Views: 2065

Answers (1)

Selçuk Cihan
Selçuk Cihan

Reputation: 2034

The second question is a matter of taste i believe.

As for implementing the slider, you can use SeekBar. Since you have 0.5 step size and a range of 48, that would give you 96 discrete points. Set the max as 96 in the SeekBar. Implement onProcessChanged accordingly and you are good to go. See the example code for reference:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="-24"
    android:id="@+id/textView2"
    android:layout_gravity="center_vertical" />

<SeekBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/seekBar"
    android:layout_gravity="center_vertical"
    android:layout_weight="1"
    android:max="96"
    android:indeterminate="false" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="24"
    android:id="@+id/textView3"
    android:layout_gravity="center_vertical" />

And here is the seek bar change listener:

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SeekBar bar = (SeekBar)this.findViewById(R.id.seekBar);
        mTextView = ((TextView)MainActivity.this.findViewById(R.id.textView));
        bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float value = -24 + (progress / 2.0f);
                MainActivity.this.mTextView.setText(String.format("%.1f", value));
            }
        });
    }
}

Upvotes: 2

Related Questions