Sunday, January 16, 2011

Android ProgressBar source code sample

The HowTo

To implement a ProgressBar, a Runnable Thread is used transmitt a message to a Handle to move the progress forward in the ProgressBar.

To do it we'll have to modify the XML layout file main.xml (under res/layout) to add those two ProgressBar.


android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressbar_default"
/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:id="@+id/progressbar_Horizontal"
android:max="100"
/>

Once finished with the layout file, we modify the main java file (MainActivity here) like this:

package com.wikinut.android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

ProgressBar myProgressBar;
int myProgress = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

myProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);

new Thread(myThread).start();
}

private Runnable myThread = new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}

Handler myHandle = new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};
}


Run that as usual and you should have something similar to this:

No comments: