SeekBar example

SeekBar
Android SeekBar is an user interface element that contains a draggable thumb and represents progress of an operation. The user can touch the thumb and drag left or right to set the current progress level. For the SeekBar, bY default, minimum progress is 0 and maximum progress is 100.

Step 1: Create a new project with name Seekbar and package name com.mycompany.myseekbar. Select File -> New -> New Project. Fill the forms and click “Finish” button.

Step 2: Open res -> layout -> xml (or) main.xml and add following code. Here we will create a SeekBar and a TextView in a LinearLayout with vertical orientation.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center"
	android:orientation="vertical">

	<SeekBar
		android:layout_height="wrap_content"
		android:layout_width="match_parent"
		android:id="@+id/mainSeekBar1"/>

	<TextView
		android:layout_height="wrap_content"
		android:layout_width="wrap_content"
		android:text="Large Text"
		android:id="@+id/mainTextView1"
		android:textColor="#000000"
		android:textSize="18sp"/>

</LinearLayout>

Step 3: Open app -> java -> package and open MainActivity.java. Add following code in it. Here when the progress of SeekBar is changed, the progress is displayed in the TextView.

package com.mycompany.myseekbar;

import android.app.*;
import android.os.*;
import android.widget.*;

public class MainActivity extends Activity 
{
	SeekBar seekbar1;
	TextView textview1;
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		
		seekbar1 = (SeekBar) findViewById(R.id.mainSeekBar1);
		textview1 = (TextView) findViewById(R.id.mainTextView1);
		
		seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				textview1.setText(String.valueOf(progress)); 
			} 
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}
			@Override 
			public void onStopTrackingTouch(SeekBar seekBar) { 
			} 
		}); 
    }
}

Output:
Now run the app. Here when you change the progress of the SeekBar, the TextView will display the progress.

Leave a Reply