Skip to main content

How to use ProgressBar in Android

Table of contents
  1. Android ProgressBar Example
    • Horizontal ProgressBar
    • Determinate ProgressBar
    • Thread
    • Thread.sleep()
    • Handler
    • Runnable
    • run()
    • try catch block
    • InterruptedException
    • printStackTrace()
    • ProgressBar.setProgress()
    • While Loop
  2. ProgressBar CountDown
  3. ProgressBar with CountDownTimer
  4. ProgressBar Color

1. Android ProgressBar Example

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:text="Start Operation"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        android:textSize="20dp"
        />
    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:indeterminate="false"
        style="@android:style/Widget.ProgressBar.Horizontal"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.os.Handler;
import android.widget.TextView;

public class MainActivity extends Activity {

    private int progressStatus = 0;
    private Handler handler = new Handler();

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

        //Get the widgets reference from XML layout
        final ProgressBar pb = (ProgressBar) findViewById(R.id.pb);
        final TextView tv = (TextView) findViewById(R.id.tv);
        final Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Start lengthy operation in a background thread
                new Thread(new Runnable() {
                    public void run() {
                        while (progressStatus < 100) {
                            //progressStatus = doWork();
                            progressStatus +=1;

                            //Try to sleep the thread for 20 milliseconds
                            try{
                                Thread.sleep(20);
                            }catch(InterruptedException e){
                                e.printStackTrace();
                            }

                            //Update the progress bar
                            handler.post(new Runnable() {
                                public void run() {
                                    pb.setProgress(progressStatus);
                                    tv.setText(progressStatus+"");
                                }
                            });
                        }
                    }
                }).start();
            }
        });
    }
}

2. ProgressBar CountDown

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:text="Start Count Down"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        android:textSize="50dp"
        android:layout_centerHorizontal="true"
        android:textColor="#ffff0049"
        />
    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:indeterminate="false"
        style="@android:style/Widget.ProgressBar.Horizontal"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.os.Handler;
import android.widget.TextView;

public class MainActivity extends Activity {

    private int progressStatus = 0;
    private Handler handler = new Handler();
    private int progressBarMaximumValue = 500;
    private int countDownStatus = progressBarMaximumValue;

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

        //Get the widgets reference from XML layout
        final ProgressBar pb = (ProgressBar) findViewById(R.id.pb);
        final TextView tv = (TextView) findViewById(R.id.tv);
        final Button btn = (Button) findViewById(R.id.btn);

        //Set the range of the progress bar to 0...max.
        pb.setMax(progressBarMaximumValue);

        //Set the TextView initial text as ProgressBar maximum value
        tv.setText(progressBarMaximumValue+"");

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Start lengthy operation in a background thread
                new Thread(new Runnable() {
                    public void run() {
                        while (progressStatus < progressBarMaximumValue) {
                            //progressStatus = doWork();
                            progressStatus +=1;
                            countDownStatus -=1;

                            //Try to sleep the thread for 20 milliseconds
                            try{
                                Thread.sleep(20);
                            }catch(InterruptedException e){
                                e.printStackTrace();
                            }

                            //Update the progress bar
                            handler.post(new Runnable() {
                                public void run() {
                                    pb.setProgress(progressStatus);
                                    //Display the count down on TextView
                                    tv.setText(countDownStatus+"");
                                }
                            });
                        }
                    }
                }).start();
            }
        });
    }
}

3. ProgressBar with CountDownTimer

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:text="Start Count Down Timer"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        android:textSize="35dp"
        android:layout_centerHorizontal="true"
        android:textColor="#ff3d41ae"
        />
    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:indeterminate="false"
        style="@android:style/Widget.ProgressBar.Horizontal"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.os.CountDownTimer;

public class MainActivity extends Activity {

    private int progressStatus = 0;
    //The number of milliseconds in the future from the
    //call to start() until the count down is done
    private long millisInFuture = 20000; //20 seconds (make it dividable by 1000)
    //The interval along the way to receive onTick() callbacks
    private long countDownInterval = 1000; //1 second (don't change this value)

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

        //Get the widgets reference from XML layout
        final ProgressBar pb = (ProgressBar) findViewById(R.id.pb);
        final TextView tv = (TextView) findViewById(R.id.tv);
        final Button btn = (Button) findViewById(R.id.btn);

        //Cast long value to int value
        //When defining above variables, make sure 'progressBarMaximumValue' always rerun integer value
        int progressBarMaximumValue = (int)(millisInFuture/countDownInterval);
        //Set ProgressBar maximum value
        //ProgressBar range (0 to maximum value)
        pb.setMax(progressBarMaximumValue);
        //Display the CountDownTimer initial value
        tv.setText(progressBarMaximumValue + "  Seconds...");

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Initialize a new CountDownTimer instance
                new CountDownTimer(millisInFuture, countDownInterval){
                    public void onTick(long millisUntilFinished){
                        //Another one second passed
                        tv.setText(millisUntilFinished/1000 + "  Seconds...");
                        //Each second ProgressBar progress counter added one
                        progressStatus +=1;
                        pb.setProgress(progressStatus);
                    }

                    public void onFinish(){
                        //Do something when count down end.
                        progressStatus +=1;
                        pb.setProgress(progressStatus);
                        tv.setText(progressStatus - pb.getMax() + "  Seconds...");
                    }
                }.start();
            }
        });
    }
}

4. ProgressBar Color

activity_main.xml [Important part only]

<ProgressBar
        android:id="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:indeterminate="false"
        style="@android:style/Widget.Material.Light.ProgressBar.Horizontal"
        />
MainActivity.java [Important part only]

final ProgressBar pb = (ProgressBar) findViewById(R.id.pb);
//pb.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
//pb.getProgressDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);
//pb.getProgressDrawable().setColorFilter(Color.MAGENTA, PorterDuff.Mode.SRC_IN);
//pb.getProgressDrawable().setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_IN);
//pb.getProgressDrawable().setColorFilter(Color.CYAN, PorterDuff.Mode.SRC_IN);
pb.getProgressDrawable().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN);
More android examples

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…