效果如图:
①:main页面布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:id="@+id/main_tv_tv1"
android:layout_width="60dp"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/main_pro_pro1"
android:layout_width="match_parent"
android:layout_height="60dp"
style="?android:attr/progressBarStyleHorizontal"//将进度条设置为长条,默认为圆形
android:max="100"
/>
</FrameLayout>
<Button
android:id="@+id/main_btn_btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="setProgress"
/>
</LinearLayout>
②
线程的注意事项:
不能在主线程中执行耗时的操作,只能在子线程中操作
另外,在子线程中不能操作主线程中的控件(ProgressBar除外)
public class MainActivity extends AppCompatActivity {
private ProgressBar main_pro_pro1;//进度条
private int progress;
private TextView main_tv_tv1;//进度条百分比
private MyHandler myHandler = new MyHandler();
private int code = 1;//线程编号
private class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(code == msg.what){
progress++;
main_pro_pro1.setProgress(progress);
main_tv_tv1.setText(progress+"%");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main_pro_pro1 = this.findViewById(R.id.main_pro_pro1);
main_tv_tv1=this.findViewById(R.id.main_tv_tv1);
}
public void setProgress(View view) {
if(0 == progress){
new MyThread().start();//触发子线程
}
}
//耗时操作放在MyThread(子线程)
private class MyThread extends Thread{
@Override
public void run() {
super.run();
while (true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(progress==100){
progress=0;
break;
}
Message msg = new Message();
msg.what=1;
myHandler.sendMessage(msg);//Handler
}
}
}
}