網上一般對進度條的樣本都是如何顯示,沒有在任務結束如何關閉的文章,參考其他文章經過實驗之後把整套進度條顯示的簡單樣本如下:
建立android工程等工作都略去,Google一下就可以了。
下面來介紹主要的Activity
ProgressBarDemo.java Java代碼
- package com.lveyo.android.demo.progressbar;
-
- import android.app.Activity;
- import android.app.ProgressDialog;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class ProgressBarDemo extends Activity {
-
- private TextView statusTextView;
- private Button beginBtn;
- private ProgressDialog progressDialog;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- statusTextView = (TextView)findViewById(R.id.status);
- beginBtn = (Button)findViewById(R.id.beginBtn);
- setListener();
- }
-
- /**
- * 用Handler來更新UI
- */
- private Handler handler = new Handler(){
-
- @Override
- public void handleMessage(Message msg) {
-
- //關閉ProgressDialog
- progressDialog.dismiss();
-
- //更新UI
- statusTextView.setText("Completed!");
- }};
-
-
- /**
- * 點擊按鈕事件listener
- */
- private void setListener(){
- beginBtn.setOnClickListener(new View.OnClickListener() {
-
- @Override
- public void onClick(View v) {
-
- //顯示ProgressDialog
- progressDialog = ProgressDialog.show(ProgressBarDemo.this, "Loading...", "Please wait...", true, false);
-
- //建立線程
- new Thread(){
-
- @Override
- public void run() {
- //需要花時間計算的方法
- Calculation.calculate(4);
-
- //向handler發訊息
- handler.sendEmptyMessage(0);
- }}.start();
- }
- });
- }
-
- }
package com.lveyo.android.demo.progressbar;import android.app.Activity;import android.app.ProgressDialog;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.TextView;public class ProgressBarDemo extends Activity { private TextView statusTextView;private Button beginBtn;private ProgressDialog progressDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); statusTextView = (TextView)findViewById(R.id.status); beginBtn = (Button)findViewById(R.id.beginBtn); setListener(); } /** * 用Handler來更新UI */ private Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {//關閉ProgressDialogprogressDialog.dismiss();//更新UIstatusTextView.setText("Completed!");}}; /** * 點擊按鈕事件listener */ private void setListener(){ beginBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//顯示ProgressDialogprogressDialog = ProgressDialog.show(ProgressBarDemo.this, "Loading...", "Please wait...", true, false);//建立線程new Thread(){@Overridepublic void run() {//需要花時間計算的方法Calculation.calculate(4);//向handler發訊息handler.sendEmptyMessage(0);}}.start();}}); } }