Android之利用Handler實現ProgressBar進度條

暖楓無敵發表於2012-06-17
res/layout/main.xml檔案內容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/pbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />
        <Button
            android:id="@+id/btnStart"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/btnText"
            />
</LinearLayout>

package syit.david;

import android.app.Activity;
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;
import android.widget.ProgressBar;

public class DemoActivity extends Activity {
    public ProgressBar pBar;
    public Button btnStart;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //查詢控制元件
        pBar = (ProgressBar)findViewById(R.id.pbar);
        btnStart = (Button)findViewById(R.id.btnStart);
        
        //為按鈕繫結監聽事件
        btnStart.setOnClickListener(new ButtonListener());
    }
    
    class ButtonListener implements OnClickListener
    {
        @Override
        public void onClick(View v)
        {
            pBar.setVisibility(View.VISIBLE);
            updateBarHandler.post(updateThread);
        }
    }
    
    //訊息非同步機制
    public Handler updateBarHandler = new  Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            pBar.setProgress(msg.arg1);
            updateBarHandler.post(updateThread);
        }
    };
    
    
    public Runnable updateThread = new Runnable()
    {
        int i =0;
        @Override
        public void run()
        {
            i+=10;
            Message msg = updateBarHandler.obtainMessage();
            msg.arg1 = i;
            try
            {
                Thread.sleep(1000);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            //將msg加入到訊息佇列中
            updateBarHandler.sendMessage(msg);
            if(i==100)
            {
                updateBarHandler.removeCallbacks(updateThread);
                pBar.setVisibility(View.GONE);
            }
        }
    };
}


相關文章