Saturday, December 12, 2015

android - Create progress drawable programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:padding="16dp"
    tools:context=".MainActivity"
    android:background="#e7f2f9"
    >
    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="200dp"
        android:layout_height="200dp"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_centerInParent="true"
        />
    <TextView
        android:id="@+id/tv_primary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:layout_centerInParent="true"
        />
    <TextView
        android:id="@+id/tv_secondary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#3981ff"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Run"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import android.os.Handler;


public class MainActivity extends AppCompatActivity {
    private Context mContext;

    private TextView mTVPrimary;
    private TextView mTVSecondary;
    private Button mButton;
    private ProgressBar mProgressBar;

    private int mProgressStatus;
    private int mSecondaryProgressStatus;

    private Handler mHandler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Change the action bar color
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));

        // Get the widgets reference from XML layout
        mTVPrimary = (TextView) findViewById(R.id.tv_primary);
        mTVSecondary = (TextView) findViewById(R.id.tv_secondary);
        mButton = (Button) findViewById(R.id.btn);
        mProgressBar = (ProgressBar) findViewById(R.id.pb);

        // Define the progress bar drawable
        mProgressBar.setProgressDrawable(new ProgressDrawableManager().generateProgressDrawable());

        // Set a click listener for button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Set the initial progress status
                mProgressStatus = 0;
                // Set the initial secondary progress status
                mSecondaryProgressStatus = 0;

                // Start the lengthy operation in a background thread
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (mProgressStatus<100){
                            // Update the progress status
                            mProgressStatus +=1;

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

                            // Update secondary progress
                            updateSecondaryProgress();
                            // Set the secondary progress status to zero after a task complete
                            mSecondaryProgressStatus = 0;

                            // Update the progress bar
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // Set the progress for progress bar
                                    mProgressBar.setProgress(mProgressStatus);
                                    mTVPrimary.setText("Complete " + mProgressStatus + "% of 100");

                                    // If primary task complete
                                    if(mProgressStatus==100){
                                        // Show message for task completion
                                        mTVPrimary.setText("Complete.");
                                    }
                                }
                            });
                        }
                    }
                }).start(); // Start the operation in a thread
            }
        });
    }

    // Custom method to update a secondary progress
    protected void updateSecondaryProgress(){
        // Start another lengthy operation in a background thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(mSecondaryProgressStatus<100){
                    mSecondaryProgressStatus +=1;

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

                    // Update the secondary progress bar
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            // Set the secondary progress bar progress
                            mProgressBar.setSecondaryProgress(mSecondaryProgressStatus);
                            mTVSecondary.setText("Single task progress " + mSecondaryProgressStatus + "% of 100");

                            // If the secondary task complete
                            if(mSecondaryProgressStatus == 100){
                                // Show a confirmation message for task completion
                                mTVSecondary.setText("Single task complete.");
                            }
                        }
                    });
                }
            }
        }).start(); // Start the operation in another thread
    }
}
ProgressDrawableManager.java

package com.cfsuman.me.androidcode;

import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.view.Gravity;


public class ProgressDrawableManager {

    // Custom method to generate progress bar progress drawable object
    protected Drawable generateProgressDrawable(){
        // Create an oval shape
        OvalShape oval = new OvalShape();

        // Create a ShapeDrawable to generate progress bar background
        ShapeDrawable backgroundDrawable = new ShapeDrawable(oval);
        backgroundDrawable.getPaint().setColor(Color.parseColor("#FFB5DDFF"));

        // Initialize a new shape drawable to draw progress bar progress
        ShapeDrawable progressDrawable = new ShapeDrawable(oval);
        //progressDrawable.getPaint().set(paint);
        progressDrawable.getPaint().setColor(Color.parseColor("#FF0A589B"));

        // Another shape drawable to draw secondary progress
        ShapeDrawable secondaryProgressDrawable = new ShapeDrawable(oval);
        secondaryProgressDrawable.getPaint().setColor(Color.parseColor("#350A589B"));

        // Initialize a ClipDrawable to generate progress on progress bar
        ClipDrawable progressClip = new ClipDrawable(progressDrawable, Gravity.BOTTOM,ClipDrawable.VERTICAL);

        // Another clip drawable to draw secondary progress
        ClipDrawable secondaryProgressClip = new ClipDrawable(secondaryProgressDrawable,Gravity.BOTTOM,ClipDrawable.VERTICAL);

        // Initialize a new LayerDrawable to hold progress bar all states
        LayerDrawable layer = new LayerDrawable(new Drawable[]{backgroundDrawable,secondaryProgressClip,progressClip});

        // Set the ids for different layers on layer drawable
        layer.setId(0,android.R.id.background);
        layer.setId(1,android.R.id.secondaryProgress);
        layer.setId(2,android.R.id.progress);

        // Return the LayerDrawable as progress bar progress drawable
        return layer;
    }
}