Wednesday, 20 July 2011

Display a indeterminate progress bar on title bar

To display a indeterminate progress bar on title bar, we have to request Window Feature of Window.FEATURE_INDETERMINATE_PROGRESS.

Place the code; before setContentView(R.layout.main):
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

then call setProgressBarIndeterminateVisibility(true/false) to turn it on/off.

Display a indeterminate progress bar on title bar

Modify from the exercise "ProgressDialog + Thread"
package com.exercise.AndroidProgressDialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.Toast;

public class AndroidProgressDialogActivity extends Activity {

ProgressDialog progressDialog;
BackgroundThread backgroundThread;

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

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);

setProgressBarIndeterminateVisibility(true);
progressDialog = ProgressDialog.show(AndroidProgressDialogActivity.this,
"ProgressDialog", "Wait!");

backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}



public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;

void setRunning(boolean b){
running = b;
cnt = 10;
}

@Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
sleep(1000);
if(cnt-- == 0){
running = false;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
handler.sendMessage(handler.obtainMessage());
}
}

Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub

setProgressBarIndeterminateVisibility(false);
progressDialog.dismiss();

boolean retry = true;
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Toast.makeText(AndroidProgressDialogActivity.this,
"dismissed", Toast.LENGTH_LONG).show();
}

};
}


next:
- Cancel ProgressDialog

No comments:

Post a Comment