Full width home advertisement

Android Development

CPP & JAVA

Post Page Advertisement [Top]


Seek Bar - Android Studio

In this article we will learn how to use a seek bar in android studio.  


SeekBar class provides a method to set seek bar change listner called onSeekBarChangeListner(). This method takes a interface OnSeekBarChangeListner. There are three override methods onProgressChanged() (Called when we change the seek bar value), onStartTrackingTouch() (Called when we grab the bar) and onStopTrackingTouch() (Called when we leave the bar). onProgressChanged() method passes a value called progress, it is value of seek bar between 0 to 100.  Below is an example code on how to use a SeekBar.


Example Code:

XML Code -  

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:gravity="center"
tools:context=".Main2Activity"
android:background="@color/blue">

<TextView
android:id="@+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="30dp"
android:textColor="@color/white"
android:layout_marginBottom="50dp"/>

<SeekBar
android:id="@+id/seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:thumbTint="@color/white"
android:progressBackgroundTint="@color/white"/>

</LinearLayout>


  JAVA Code -
  

 package com.example.test;


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


public class Main2Activity extends AppCompatActivity {

TextView textView;
SeekBar seekBar;

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

textView = findViewById(R.id.count);
seekBar = findViewById(R.id.seek_bar);

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(progress+"");
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"Start", Toast.LENGTH_SHORT).show();
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"Left", Toast.LENGTH_SHORT).show();
}
});

}
}

Result -






YouTube video link 









No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib