main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="30dip"
android:padding="0dip"
>
<ProgressBar android:id="@+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:indeterminateOnly="false"
android:layout_height="30dip" />
<TextView
android:id="@+id/perc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#ff0000"
android:textStyle="bold"
/>
</RelativeLayout>
代码:
package wxk.com;
import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
public class ThreadDemoActivity extends Activity {
ProgressBar bar;
TextView percent;
Handler handler=new Handler() {
@Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
percent.setText(String.format("%03d%%", bar.getProgress()));
}
};
boolean isRunning=false;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
bar=(ProgressBar)findViewById(R.id.progress);
percent=(TextView)findViewById(R.id.perc);
}
public void onStart() {
super.onStart();
bar.setProgress(0);
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning;i++) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
// just end the background thread
}
}
});
isRunning=true;
background.start();
}
public void onStop() {
super.onStop();
isRunning=false;
}
}