Monday, December 9, 2013

Seekbar in android

Here is the full tutorial for seekbar in android.It is used to set range of value.You can also set background image of seekbar for some value.

Here is the tutorial for seekbar,It displays the value of seekbar in Edittext and also change the color of seekbar.

Source Code:


  • Create one project and copy below code in activity_main.xml file

activity_main.xml



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

    <SeekBar
        android:id="@+id/seek_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1.71"
        android:max="100"
        android:progress="0" />

    <EditText
        android:id="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.21" />

</LinearLayout>


  • Write below code in MainActivity.java file.

MainActivity.java


import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {

SeekBar sb;
EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = (SeekBar)findViewById(R.id.seek_bar);
et= (EditText)findViewById(R.id.et);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
et.setText(""+progress);
if(progress>=50 && progress<70){
sb.setBackgroundColor(Color.RED);
}else if(progress>=70){
sb.setBackgroundColor(Color.YELLOW);
}else if(progress<50){
sb.setBackgroundColor(Color.TRANSPARENT);
}
}
});
}
}

  • That's It. Now run the project and see the output.


No comments:

Post a Comment