ProgressDialog往往通過線程現實進度什麼的,比如大文件拷貝或者網絡訪問下載等,但是用handler和線程搭配顯得比較麻煩,剛閒著無聊寫了個簡潔的方法。
- public class main extends Activity {
- private static boolean isCannel = false;
- private ProgressDialog progressDialog;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentVIEw(R.layout.main);
-
- progressDialog = new ProgressDialog (this);
- CharSequence title = "ProgressDialog監聽線程處理進度";
- //CharSequence message = getString(R.string.xxx);
- CharSequence message = "當前處理進度";
-
- ProcessThread mThread = new ProcessThread();
- progressDialog = new ProgressDialog(this);
- progressDialog.setTitle(title);
- progressDialog.setMessage(message);
- progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- progressDialog.setButton((CharSequence)"取消", mThread);
- progressDialog.setProgress(0);
- progressDialog.setMax(100);
- progressDialog.setOnCancelListener(mThread);
- progressDialog.setOnDismissListener(mThread);
- progressDialog.show();
- mThread.start();
- }
-
- private class ProcessThread extends Thread implements OnCancelListener, OnDismissListener, OnClickListener{
- public void run() {
- isCannel = false;
- int process = 0;
- while(!isCannel && process < 100) {
- progressDialog.incrementProgressBy(1);
- try {
- sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- process ++;
- }
- progressDialog.dismiss();
- finish();
- }
-
- public void onClick(DialogInterface dialog, int which) {
- isCannel = true;
- }
- public void onDismiss(DialogInterface dialog) {
- isCannel = true;
- }
- public void onCancel(DialogInterface dialog) {
- isCannel = true;
- }
- }
- }