package com.example.progressdemo;
import java.util.Iterator;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button btn_start;
private ProgressBar mBar;
private TextView tv_show_progress;
//聲明一個handler,用於在線程中發送消息修改界面的textView中的值
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
//根據progressBar的進度來設置textView中的值
//設置progressBar的進度
mBar.setProgress(msg.what);
tv_show_progress.setText(msg.what+"");
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
mBar = (ProgressBar) findViewById(R.id.progressBar1);
tv_show_progress = (TextView) findViewById(R.id.textView_show_progress);
btn_start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//在單擊事件中開一個線程來模擬後台掃描文件
new Thread() {
public void run() {
//掃描過程中不能再次啟動掃描,所以將BUTTON設置為不可點擊
btn_start.setClickable(false);/////這句為什麼不能用setenable
for (int i = 0; i < 101; i++) {
//在子線程中不能修改UI線程中數據,所以需要一個handler來發送消息修改
mHandler.sendEmptyMessage(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//掃描完成後將BUTTON還原成可點擊的狀態
btn_start.setClickable(true);
};
}.start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
setEnable設置用戶是否可以點擊此按鈕,setClickable設置程序在某個條件下自動點擊此按鈕