MainActivity.java
package com.example.progressbar;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private int [] data = new int[100];
int hasData = 0;
int status = 0;
ProgressBar bar;
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x111) {
bar.setProgress(status);
System.out.println("handler->message->" + status);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar = (ProgressBar)findViewById(R.id.bar);
new Thread() {
public void run() {
while (status < 100) {
status = doWork();
mHandler.sendEmptyMessage(0x111);
}
}
}.start();
}
public int doWork() {
data[hasData++] = (int) (Math.random()*100);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
return hasData;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Layout文件
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Large"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Small"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="任务完成的进度"
/> -->
<ProgressBar
android:id="@+id/bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
style="@android:style/Widget.ProgressBar.Horizontal"
/>
</LinearLayout>
</LinearLayout>