Sunday, February 16, 2014

ProgressBar Example in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" >
    </ProgressBar>
   
   <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" >
      </TextView>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startProgress"
        android:text="@string/sp" >

    </Button>

</LinearLayout>


MainActivity.java

package com.emahi.handler;

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

public class MainActivity extends Activity {

private ProgressBar progress;
private TextView text;

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

progress = (ProgressBar) findViewById(R.id.progressBar1);
   text = (TextView) findViewById(R.id.textView1);
}

public void startProgress(View view) {
   // do something long
   Runnable runnable = new Runnable() {
     @Override
     public void run() {
       for (int i = 0; i <= 10; i++) {
         final int value = i;
          doFakeWork();
         progress.post(new Runnable() {
           @Override
           public void run() {
             text.setText("Updating");
             progress.setProgress(value);
           }
         });
       }
     }
   };
   new Thread(runnable).start();
 }

 // Simulating something timeconsuming
 private void doFakeWork() {
   try {
     Thread.sleep(2000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


Output:


No comments:

Post a Comment