Android进度条学习一

DoLengthyWork.java

 

package tw.android;

import java.util.Calendar;

import android.os.Handler;
import android.widget.ProgressBar;

public class DoLengthyWork extends Thread {

    private Handler mHandler;//对象mHandler用来运行post更新ProgressBar的工作
    private ProgressBar mProBar;//该对象用来存储要用来处理的ProgressBar
    //用来读取系统时间的循环,并持续post更新ProgressBar的工作。
    public void run () {
        Calendar begin = Calendar.getInstance();//用来读取系统的时间
        do {
            Calendar now = Calendar.getInstance();
            final int iDiffSec = 60 * (now.get(Calendar.MINUTE) - begin.get(Calendar.MINUTE)) +
                            now.get(Calendar.SECOND) - begin.get(Calendar.SECOND);
        
            if (iDiffSec * 2 > 100) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mProBar.setProgress(100);
                    }
                });
                
                break;
            }
            
            mHandler.post(new Runnable() {
                public void run() {
                    mProBar.setProgress(iDiffSec * 2);
                }
            });
            
            if (iDiffSec * 4 < 100)
                mHandler.post(new Runnable() {
                    public void run() {
                        mProBar.setSecondaryProgress(iDiffSec * 4);
                    }
                });
            else
                mHandler.post(new Runnable() {
                    public void run() {
                        mProBar.setSecondaryProgress(100);
                    }
                });
        } while (true);
    }
    
    void setProgressBar(ProgressBar proBar) {
        mProBar = proBar;
    }
    
    void setHandler(Handler h) {
        mHandler = h;
    }
}

 

Main.java

 

package tw.android;

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

public class Main extends Activity {

    private Handler mHandler = new Handler();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        setupViewComponent();
    }
    
    private void setupViewComponent() {
        // 從資源類別R中取得介面元件
        final ProgressBar proBar = (ProgressBar)findViewById(R.id.proBar2);

        DoLengthyWork work = new DoLengthyWork();
        work.setHandler(mHandler);
        work.setProgressBar(proBar);
        work.start();
    }
}

在Mina.java中建立一个Handler对象,并且在setupViewComponent()他的内部设置了两个对象。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。