Android Seekbar

An Android SeekBar is a widget that provides a slider control for the user to select a value from a range of values. It consists of a draggable thumb, which the user can move along a horizontal or vertical line to select a value. Here is an example of how to use a SeekBar in Android:

Example:

  1. Add the SeekBar element to your layout XML file:
  2. <SeekBar
      android:id="@+id/seekBar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:max="100"
      android:progress="50" />
    

This code creates a SeekBar with a maximum value of 100 and an initial progress value of 50.

  1. In your activity or fragment, create a reference to the SeekBar:
  2. SeekBar seekBar = findViewById(R.id.seekBar);  
  3. Optionally, you can set the progress programmatically:
  4. seekBar.setProgress(75);  
  5. To get the current progress value, you can use the getProgress() method:
  6. int progress = seekBar.getProgress();  
  7. You can also set a listener to be notified when the progress changes:
  8. seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // Do something when the progress changes
        }
    
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // Called when the user starts dragging the thumb
        }
    
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // Called when the user stops dragging the thumb
        }
    });

This code sets a listener that is notified when the user changes the progress of the SeekBar.

Uses:

  • SeekBars are commonly used to select a value from a range of values, such as selecting a font size or volume level.
  • They can be customized to fit the design of your app by using custom drawables or styles.
  • SeekBars can also be used in combination with other UI elements, such as TextViews, to display the selected value in real time.
Next Article ❯