核心代码:
// 对话框进度条控件
private ProgressDialog progressDialog;
/**
* 显示进度条对话框
*
* @param title
* 进度条对话框标题
* @param message
* 进度条对话框消息
* */
public void showProgressDialog(String title, String message) {
if (progressDialog == null) {
progressDialog = ProgressDialog.show(this, title, message);
} else {
progressDialog.setTitle(title);
progressDialog.setMessage(message);
}
}
/** 关闭进度条对话框 */
public void closedProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
建立android工程等工作都略去,Google一下就可以了。
下面来介绍主要的Activity
ProgressBarDemo.java
Java代码
package com.lveyo.android.demo.progressbar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
publicclass ProgressBarDemo extends Activity {
private TextView statusTextView;
private Button beginBtn;
private ProgressDialog progressDialog;
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
statusTextView = (TextView)findViewById(R.id.status);
beginBtn = (Button)findViewById(R.id.beginBtn);
setListener();
}
/**
* 用Handler来更新UI
*/
private Handler handler = new Handler(){
@Override
publicvoid handleMessage(Message msg) {
//关闭ProgressDialog
progressDialog.dismiss();
//更新UI
statusTextView.setText("Completed!");
}};
/**
* 点击按钮事件listener
*/
privatevoid setListener(){
beginBtn.setOnClickListener(new View.OnClickListener() {
@Override
publicvoid onClick(View v) {
//显示ProgressDialog
progressDialog = ProgressDialog.show(ProgressBarDemo.this, "Loading...", "Please wait...", true, false);
//新建线程
new Thread(){
@Override
publicvoid run() {
//需要花时间计算的方法
Calculation.calculate(4);
//向handler发消息
handler.sendEmptyMessage(0);
}}.start();
}
});
}
}
Calculation.java
Java代码
package com.lveyo.android.demo.progressbar;
/**
* 示意方法
* @author lveyo
*
*/
publicclass Calculation {
publicstaticvoid calculate(int sleepSeconds){
try {
Thread.sleep(sleepSeconds * 1000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
main.xml文件
Xml代码
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextViewandroid:id="@+id/status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Buttonandroid:id="@+id/beginBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="begin"
/>
</LinearLayout>