Coding Tutorials

SeekBar Tutorial With Example

Aditya Singh
SeekBar Tutorial With Example

In this tutorial, we’ll explore how to use a SeekBar in Android applications. A SeekBar is a user interface element that allows users to select a value from a continuous range by sliding a thumb along a horizontal track. It’s commonly used for settings like adjusting volume or brightness.

What is a SeekBar?

SeekBar is a widget that lets users pick a value by moving a slider thumb along a track. It’s an extension of the ProgressBar but with added user interaction. As users drag the thumb, the app can respond to changes in the progress level.

Implementing SeekBar in Android

Let’s create a simple app where moving the SeekBar changes the size of some text on the screen.

Step 1: Create a New Project

  1. Name your project (e.g., SeekBarExample), select Java as the language, and click Finish.
  2. Open Android Studio.
  3. Click on File > New > New Project.
  4. Choose Empty Activity and click Next.

Step 2: Design the Layout

Open the activity_main.xml file and set up the layout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- TextView to display text -->
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello SeekBar!"
        android:textSize="20sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="50dp"
        android:layout_marginStart="20dp"/>

    <!-- SeekBar to adjust text size -->
    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:max="50"
        android:progress="20"
        app:layout_constraintTop_toBottomOf="@id/textView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="20dp"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"/>
        
</androidx.constraintlayout.widget.ConstraintLayout>

Explanation:

SeekBar: Allows the user to adjust the text size. The max attribute sets the maximum value, and progress sets the initial value.

TextView: Displays the text whose size we’ll change.

Step 3: Implement Functionality in Java

Open MainActivity.java and add the following code:

package com.example.seekbarexample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private SeekBar seekBar;
    private TextView textView;
    private int progressValue;

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

         // Initialize views
        seekBar = findViewById(R.id.seekBar);
        textView = findViewById(R.id.textView);

        // Set initial text size
        textView.setTextSize(seekBar.getProgress());

        // Set SeekBar change listener
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            // When progress is changed
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progressValue = progress;
                textView.setTextSize(progress);
            }

            // When user starts tracking
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // Optional: actions when touch starts
            }

            // When user stops tracking
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(MainActivity.this, "Text size: " + progressValue + "sp", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Explanation:

  • seekBar and textView: References to the UI elements.
  • progressValue: Stores the current progress.
  • setOnSeekBarChangeListener: Responds to SeekBar events.
    • onProgressChanged: Updates text size as the SeekBar moves.
    • onStartTrackingTouch: Called when the user touches the SeekBar.
    • onStopTrackingTouch: Shows a Toast with the selected text size.

Step 4: Run the App

  1. Connect your device or start an emulator.
  2. Click Run > Run ‘app’.
  3. The app will display the text and SeekBar.
  4. Move the SeekBar to see the text size change.

Understanding SeekBar Listener Methods

The SeekBar.OnSeekBarChangeListener interface has three methods:

  1. onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
    • Called when the progress level changes.
    • progress: Current progress value.
    • fromUsertrue if the change was initiated by the user.
  2. onStartTrackingTouch(SeekBar seekBar)
    • Called when the user first touches the SeekBar.
  3. onStopTrackingTouch(SeekBar seekBar)
    • Called when the user stops touching the SeekBar.

Customizing the SeekBar

You can customize the SeekBars appearance and behavior.

Changing the Thumb and Track Color

To change the thumb (the draggable part) and track color, you can use:

android:thumbTint="@color/your_color"
android:progressTint="@color/your_color"

Add these attributes to the SeekBar in activity_main.xml.

Setting Minimum and Maximum Values

By default, the SeekBar ranges from 0 to the value set in android:max. If you want a different range, adjust your calculations in the code.

Using Discrete Steps

If you want the SeekBar to move in steps rather than smoothly, you can increment the progress manually.

javaCopy codeseekBar.incrementProgressBy(stepSize);

Tips for Using SeekBar

  • Validate Input: Always check that the progress value is within expected bounds.
  • User Feedback: Update UI elements or show messages to reflect changes.
  • Accessibility: Ensure the SeekBar is accessible for users with disabilities.

Conclusion

You’ve now learned how to implement and customize a SeekBar in your Android app. SeekBars are versatile and can enhance user experience by providing intuitive controls for adjusting values.

Additional Resources

  • Official DocumentationSeekBar Class
  • Custom Widgets: Learn more about customizing Android widgets.
  • User Interface Best Practices: Enhance your app’s usability.