本文通过一个小例子来学习Handler的使用--Handler来控制进度条(ProgressBar)的进度。
1.布局文件activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="cn.sehzh.handlertester.MainActivity" > <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="16dp" android:max="300" /> <Button android:id="@+id/startButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/progressBar" android:layout_centerHorizontal="true" android:layout_marginTop="117dp" android:text="Start" /> </RelativeLayout> 2.MainActivity package cn.sehzh.handlertester; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; public class MainActivity extends Activity { private ProgressBar mProgressBar; private Button mStartBtn; private int mProgressBarStatus = 0; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { findView(); mHandler = new Handler(); mStartBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mStartBtn.setClickable(false); new Thread(new Runnable() { public void run() { try { while (mProgressBarStatus < mProgressBar.getMax()) { mProgressBarStatus += 5; Thread.sleep(1000); mHandler.post(new Runnable() { public void run() { mProgressBar.setProgress(mProgressBarStatus); } }); } } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }); } private void findView() { mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mStartBtn = (Button) findViewById(R.id.startButton); } } 3.实现效果
