strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">IntentProgressBar</string>
<string name="start">开始</string>
</resources>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ProgressBar android:id="@+id/progressBarId"
android:layout_width="fill_parent" android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal" android:max="200"
android:visibility="gone" />
<Button android:id="@+id/startButtonId" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/start" />
</LinearLayout>
IntentProgressBarActivity.java
package com.duoguo.android;
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;
/**
* Intent在ProgressBar中的使用
*
* @author shyboy([email protected])
*
*/
public class IntentProgressBarActivity extends Activity {
private ProgressBar progressBar;// 声明ProgressBar控件
private Button startButton;// 声明Button控件
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBarId);// 根据控件id获取ProgressBar控件对象
startButton = (Button) findViewById(R.id.startButtonId);// 根据控件id获取Button控件对象
startButton.setOnClickListener(new StartButtonClickListener());// 为startButton按钮控件添加单击事件监听器
}
// 声明startButton控件的事件监听器
class StartButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);// 设置progressBar进度条为可见
handler.post(runnable);// 将线程添加到线程队列中
}
}
// 实例化Handler对象,通过handleMessage用来接收队列中的消息
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progressBar.setProgress(msg.arg1);// 设置progressBar进度条的第一进度值
handler.post(runnable);// 将线程添加到线程队列当中
}
};
// 实例化线程runnable对象
Runnable runnable = new Runnable() {
int i = 0;
@Override
public void run() {
System.out.println("thread start");
i += 10;
Message message = handler.obtainMessage();// 获取消息对象
message.arg1 = i;// 用成员变量arg1来存放i的值
try {
Thread.sleep(1000);// 线程休眠1s
handler.sendMessage(message);// 将消息添加到消息队列的尾端
if (i == progressBar.getMax()) {
handler.removeCallbacks(runnable);// 将线程对象从消息队列中移除
progressBar.setVisibility(View.GONE);
i = 0;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
希望对你有所帮助,呵呵……