handler机制在很多时候都用来跟新UI,这里把ProgressBar与handler混搭,重点来看handler的使用。
public class mProgressBarActivity extends Activity implements OnClickListener { private TextView mTextView01; private Button mButton01; private ProgressBar mProgressBar01; public int intCounter=0; /* 自定义Handler信息代码,用以作为识别事件处理 */ protected static final int GUI_STOP_NOTIFIER = 0x108; protected static final int GUI_THREADING_NOTIFIER = 0x109; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mButton01 = (Button)findViewById(R.id.myButton1); mTextView01 = (TextView)findViewById(R.id.myTextView1); mProgressBar01 = (ProgressBar)findViewById(R.id.myProgressBar1); mButton01.setOnClickListener(this); } public void onClick(View v) { int viewId = v.getId(); switch (viewId) { case R.id.myButton1: mTextView01.setText(R.string.str_progress_start); mProgressBar01.setVisibility(View.VISIBLE); mProgressBar01.setMax(100); mProgressBar01.setProgress(0); new Thread(new Runnable() { public void run() { for (int i=0;i<10;i++) { try { intCounter = (i+1)*20; Thread.sleep(1000); if(i==4) { Message m = new Message(); m.what = mProgressBarActivity.GUI_STOP_NOTIFIER; mProgressBarActivity.this.myMessageHandler.sendMessage(m); break; } else { Message m = new Message(); m.what = mProgressBarActivity.GUI_THREADING_NOTIFIER; mProgressBarActivity.this.myMessageHandler.sendMessage(m); } } catch(Exception e) { e.printStackTrace(); } } } }).start(); default: break; } } Handler myMessageHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case mProgressBarActivity.GUI_STOP_NOTIFIER: mTextView01.setText(R.string.str_progress_done); mProgressBar01.setVisibility(View.GONE); Thread.currentThread().interrupt(); break; case mProgressBarActivity.GUI_THREADING_NOTIFIER: if(!Thread.currentThread().isInterrupted()) { mProgressBar01.setProgress(intCounter); mTextView01.setText ( getResources().getText(R.string.str_progress_start)+ "("+Integer.toString(intCounter)+"%)\n"+ "Progress:"+ Integer.toString(mProgressBar01.getProgress())+ "\n"+"Indeterminate:"+ Boolean.toString(mProgressBar01.isIndeterminate()) ); } break; } super.handleMessage(msg); } }; }
在写事件监听时候,最有效的编码规范是把:事件的定义和实现分开,让代码看起来醒目了然!