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);
}
}
};
}