How to create progress bar programmatically in android

How to create and use horizontal progress bar dynamically on android using MainActivity.java programming coding file.

In this tutorial we are creating progress bar at application run time using MainActivity.java coding file, So there are no need to define progress bar manually on activity layout file. So here is the complete step by step tutorial for How to create progress bar programmatically in android.

android-project-download-code-button

How to create progress bar programmatically in android.

Code for MainActivity.java file.

 package com.progressbarprogrammatically_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.graphics.Color;
import android.graphics.PorterDuff;


public class MainActivity extends Activity {

 ProgressBar progressbar;
 int intValue = 0;
 Handler handler = new Handler();
 LayoutParams layoutparams;
 RelativeLayout relativelayout;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 relativelayout = (RelativeLayout)findViewById(R.id.relativeLayout);
 // Creating progress bar via coding method.
 progressbar = new ProgressBar(MainActivity.this, null, android.R.attr.progressBarStyleHorizontal);
 
 progressbar.getProgressDrawable().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
 
 layoutparams = new LayoutParams(450,LayoutParams.WRAP_CONTENT);

 layoutparams.setMargins(0,100,0,0);
 
 progressbar.setLayoutParams(layoutparams);
 
 relativelayout.addView(progressbar);
 
 new Thread(new Runnable() {
 
 @Override
 public void run() {
 // TODO Auto-generated method stub
 while(intValue < 100)
 {
 intValue++;
 
 handler.post(new Runnable() {
 
 @Override
 public void run() {
 
 
 progressbar.setProgress(intValue);
 
 }
 });try {
 Thread.sleep(300);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 }
 }).start();
 }
 
 }

Code for activity_main.xml layout file.

 <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:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.progressbarprogrammatically_android_examples.com.MainActivity"
 android:id="@+id/relativeLayout" >

 

</RelativeLayout>

Screenshot:

How to create progress bar programmatically in android

Click here to download How to create progress bar programmatically in android project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *