摘要:ProgressBar的應用
下載進度Bar的實作:
xml的部分:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txtview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
</LinearLayout>
主程式部分:
package tw.nkfust.jason;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ProgressBarSampleIIActivity extends Activity implements Runnable {
/** Called when the activity is first created. */
TextView txtview1;
Button btn1;
ProgressBar pgb1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtview1 = (TextView) findViewById(R.id.txtview1);
btn1 = (Button) findViewById(R.id.button1);
pgb1 = (ProgressBar) findViewById(R.id.progressBar1);
btn1.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
txtview1.setText("下載中...");
Thread th1 = new Thread(ProgressBarSampleIIActivity.this);
th1.start();
}
});
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
try {
if(i<7)
Thread.sleep(500);
else
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int percent=(i+1)*10;
Message m = new Message();
m.obj=(Integer)percent;
handler.sendMessage(m);
}
}
private Handler handler = new Handler(){
public void handleMessage(Message msg){
int x=Integer.parseInt(msg.obj.toString());
if(x==100){
txtview1.setText("完成!");
pgb1.setProgress(x);
}else{
txtview1.setText("下載進度:"+x+"%");
pgb1.setProgress(x);
}
}
};
}