1、activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="进度条" />
</LinearLayout>
2、MainActivity.java类的实现
包
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
类的实现
public class MainActivity extends Activity {
private Button btn1;
final int MAX_PROGRESS = 333;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
// 进度条
ProgressDialog progress;
// 是否取消进度
Boolean bCancle = false;
@Override
public void onClick(View v) {
progress = new ProgressDialog(MainActivity.this);
progress.setIcon(R.drawable.ic_launcher);
progress.setTitle("进度条窗口");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setMax(MAX_PROGRESS);
progress.setButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
bCancle = true;
}
});
progress.show();
// 创建一个线程
Thread thread = new Thread(r);
thread.start();
}
// 线程响应
Runnable r = new Runnable() {
public void run() {
int nStep = 0;
while (nStep < MAX_PROGRESS) {
if (bCancle) {
break;
}
try {
Thread.sleep(100);
nStep++;
progress.incrementProgressBy(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
});
}
}
3、效果图