SeekBar Tutorial With Example - Android Hire
Coding Tutorials

SeekBar Tutorial With Example

Aditya Singh
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?

A 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.

" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button">
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
        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
        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.
Aditya Singh's profile picture

Aditya Singh

With over seven years of experience, I help people understand technology through clear and insightful articles. I cover the latest in technology, mobile devices, PCs, how-tos, guides, news, and gadget reviews, always staying updated to provide accurate and reliable information.

Related Posts

7 Top Samsung Galaxy Ring Alternatives for 2025

7 Top Samsung Galaxy Ring Alternatives for 2025

Tired of waiting for the Samsung Galaxy Ring to hit the market? You’re not alone. While the buzz around Samsung’s smart ring continues, a plethora of impressive alternatives is already available. These devices deliver advanced health tracking, stylish designs, and unique features that cater to various lifestyles. The current lineup of smart rings caters to […]

What Is Quiet Mode on Instagram and How to Activate It

What Is Quiet Mode on Instagram and How to Activate It

Ever wondered what Quiet Mode on Instagram is all about? This simple yet powerful Instagram feature helps you take a break from the constant buzz of notifications and focus on what truly matters. Whether you’re striving for better work-life balance, dedicating time to studying, or simply trying to disconnect from social media distractions, Quiet Mode […]

How to Make a Bed in Minecraft (Step-by-Step Guide)

How to Make a Bed in Minecraft (Step-by-Step Guide)

A bed in Minecraft is very important. It lets you skip the night and set your spawn point, so if you die, you will return to your bed instead of the original world spawn. This guide will show you how to gather materials, craft a bed, and set your spawn point. We’ll also show you how to customize your bed, build bunk […]

10 Best MMORPG Games For Android

10 Best MMORPG Games For Android

Not too long ago, MMORPG games and powerful gaming consoles were mostly exclusive to PCs. They required high-end graphics and systems to deliver their immersive gameplay. But times have changed. With the rise of gaming-oriented smartphones, you can now enjoy PC-like gaming experiences on your Android device. Thanks to these technological advancements and faster internet […]

Roblox: Fruit Battlegrounds codes (January 2025)

Roblox: Fruit Battlegrounds codes (January 2025)

Fruit Battlegrounds codes are all about getting more gems and help you to shoot up your rank in this One Piece anime-inspired game. This Fruit Battlegrounds was made by Popo developer. It is an action-packed game where players battle it out using unique fruit-based abilities. With constant updates, new fruits, and exciting challenges, it’s a fruity frenzy you won’t […]

Roblox: Ultimate Football Codes (January 2025)

Roblox: Ultimate Football Codes (January 2025)

Want to get some extra items for Ultimate Football in Roblox? You’ve come to the right place! Here’s the latest list of codes to help you score touchdowns and look stylish on the field. These codes offer free rewards such as coins and cosmetics to enhance your gameplay. What are Ultimate Football Codes? Ultimate Football […]

Roblox: Da Hood Codes (January 2025)

Roblox: Da Hood Codes (January 2025)

Are you a fan of Roblox games, in this article we will look at the Roblox Da Hood Codes for December 2024 that will help you unlock exclusive items, improve your gameplay and dominate the streets of Da Hood. You can feel that the game is inspired by the Grand Theft Auto series and there […]