Monday, 22 February 2016

Progress Dialog in Android

activity_main.xml

<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"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Progress Dialog Demo" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="59dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="Button"
        android:onClick="download" />

</RelativeLayout>


MainActivity.Java


package com.example.progressbar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
Button b1;
  private ProgressDialog progress;
  
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     b1 = (Button) findViewById(R.id.button1);
     
    
  }
  
  public void download(View view){
     progress=new ProgressDialog(this);
     progress.setMessage("Downloading Music");
     progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     progress.setIndeterminate(true);
     progress.setProgress(0);
     progress.show();
     
     final int totalProgressTime = 100;
     final Thread t = new Thread() {
        @Override
        public void run() {
           int jumpTime = 0;
           
           while(jumpTime < totalProgressTime) {
              try {
                 sleep(200);
                 jumpTime += 5;
                 progress.setProgress(jumpTime);
              }
              catch (InterruptedException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
              }
           }
        }
     };
     t.start();
  }
}


Output:




in MainActivity.java just am changing the style in below line.

Instead of this line
 progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

am putting below line so out is :
  progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);



No comments:

Post a Comment

Ads Inside Post