android基本控件示例progressbar進度條(03)

//progressbar進度條示例

public class MainActivity extends Activity {
    private static final String tag = "MainActivity";
	private ProgressBar pb;
    private boolean start;//點擊按鈕開始標記
    private Timer timer;//計時監聽
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pb=(ProgressBar) this.findViewById(R.id.proBar);
		pb.setMax(100);//要設置最大進度,100
	}
	//開始按鈕事件
	public void start(View view){
          if(start){
        	  return;
          }
          //設置刻度
          pb.setProgress(0);//從0位置開始
        //每隔一段時間更新 進度
          timer=new Timer();//計時器
          timer.schedule(new MyTask(), 0, 200);//long類型,每隔200毫秒更新一次
          start = true;//啓動後賦值爲true;防止下一次沒運行完時再按
          
	}
	//開啓一個線程
	private class MyTask extends TimerTask{

		@Override
		public void run() {
			//獲取進度條上的當前進度
			int currentProgress=pb.getProgress();
			if(currentProgress==pb.getMax()){//到了進度盡頭時,中止
				this.cancel();
				start=false;
				return;
			}
			currentProgress++;
			pb.setProgress(currentProgress);
		}

	}
}
/佈局文件:
  <ProgressBar
        android:id="@+id/proBar"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/sure"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="start"
        android:text="開始" />
相關文章
相關標籤/搜索