布局文件比較簡單,只有一個按鈕:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <Button android:text="Login"
- android:id="@+id/loginBtn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
本程序參照mars老師的視頻寫的,下面是主程序代碼:
- package com.cloay;
-
- import android.app.Activity;
- import android.app.ProgressDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
-
- /**
- * Myhandler.java
- * @author Cloay
- * 2011-9-6
- */
- public class Myhandler extends Activity{
- private Button button;
- private ProgressDialog progressDialog;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.handler);
- button = (Button)findViewById(R.id.loginBtn);
- button.setOnClickListener(new loginBtnListener());
- }
- /*
- * 使用Handler更新UI
- */
- Handler handler = new Handler(){
-
- @Override
- public void handleMessage(Message msg) {
- //設置進度條當前值,並將線程對象放入線程隊列
- progressDialog.setProgress(msg.arg1);
- handler.post(updateThread);
- }
-
- };
- class loginBtnListener implements OnClickListener{
-
- @Override
- public void onClick(View v) {
- handler.post(updateThread);
- progressDialog = new ProgressDialog(Myhandler.this);
- progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- progressDialog.setMessage("正在登陸,請稍後...");
- progressDialog.setTitle("登陸系統");
- progressDialog.setIcon(R.drawable.ask);
- progressDialog.setMax(100);
- progressDialog.setProgress(0);
- progressDialog.setCancelable(true);
- progressDialog.setButton("取消", new DialogInterface.OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog, int which) {
- // TODO Auto-generated method stub
- dialog.dismiss();
- }
- });
- progressDialog.show();
- }
-
- }
- Runnable updateThread = new Runnable() {
- int i = 0;
- @Override
- public void run() {
- i += 5;
- Message msg = handler.obtainMessage(); //得到一個消息對象
- //將msg對象的參數設置為i,Message類共有兩個參數arg1和arg2,用這兩個成員變量傳遞消息的優點是系統性能消耗最少
- msg.arg1 = i;
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //將msg壓入消息隊列,sendMessage方法是異步的,不等消息被處理,該方法就返回,繼續往下執行
- handler.sendMessage(msg);
- if(i == progressDialog.getMax()){
- //當i達到最大值時,從消息隊列中刪除msg
- handler.removeCallbacks(updateThread, msg);
- progressDialog.dismiss();
- }
- }
-
- };
- }
運行效果圖如下: