1.进度条(ProgressBar)
进度条的属性:
style=”?android:attr/progressBarStyleHorizontal” 默认为圆形
android:progress=”33” 进度条进行到的当前位置(去activity中动态加载)
android:max=”100” 进度条的最大长度为 100
<ProgressBar
android:id="@+id/ptn_main_ptn1"
android:layout_width="match_parent"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:progress="33"
android:layout_height="60dp" />
2 线程注意事项:
不能在主线程中执行耗时的操作,只能在子线程中操作
另外,在子线程中不能操作主线程中的控件(ProgressBar除外
解决办法用Handler:
Handler:用于线程之间的通信,比如:主线程与子线程
3:案例 点击下载按钮,进度条以及进度条的百分比动态改变
(1)首先在activity中弄一个Button,一个TextView,一个ProgressBar
并且给按钮添加一个点击事件set
(2) 然后在MainActivity.java中实现方法
package com.basic.t212_a05;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ProgressBar ptn_main_ptn1;
private int progress;
private TextView tv_main_tv1;
private int code = 1;
private myHandler myHandler = new myHandler();
private class myHandler extends Handler{
@Override
//通过handler去执行主线程中的操作
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(code==msg.what){
progress++;
ptn_main_ptn1.setProgress(progress);
tv_main_tv1.setText(progress + "%");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//根据id找到对应的控件
ptn_main_ptn1 = this.findViewById(R.id.ptn_main_ptn1);
tv_main_tv1 = this.findViewById(R.id.tv_main_tv1);
}
public void set(View view) {
if(0 == progress){
new myThread();
}
}
private class myThread extends Thread{
@Override
public void run() {
super.run();
while(true){
try {
Thread.sleep(100);//线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
//如果进度条加载到100就归0并停止运行
if(progress == 100){
progress=0;
break;
}
progress++;
ptn_main_ptn1.setProgress(30);
Message msg = new Message();
msg.what = 1;//指定的线程
myHandler.sendMessage(msg);
}
}
}
}
4:线程小结
SubThread->MainThread 错误
SubThread->Handler->MainThread 正确