Thursday, May 14, 2015

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