?
package com.example.jingdutiao;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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 MainActivity extends AppCompatActivity {
private ProgressBar progress;
private TextView tv_show;
private Button btn_down;
// 进度条当前进度值
private int pb = 0;
Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
tv_show.setText(msg.arg1+"%");
progress.setProgress(msg.arg1);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
while (pb<=100){
Message message = Message.obtain();
message.arg1 = pb;
handler.sendMessage(message);
try {
Thread.sleep(1000);
pb++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
btn_down.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread thread = new Thread(runnable);
thread.start();
}
});
}
public void init(){
progress = findViewById(R.id.progress);
tv_show = findViewById(R.id.tv_show);
btn_down = findViewById(R.id.btn_down);
}
}
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- 转圈进度条-->
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- 条形进度条-->
<ProgressBar
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- progress设置当前进度,secondaryProgress设置缓存进度-->
<ProgressBar
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="20"
android:secondaryProgress="40"/>
<ProgressBar
android:id="@+id/progress"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="0" />
<TextView
android:id="@+id/tv_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20dp"/>
<Button
android:id="@+id/btn_down"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载"/>
</LinearLayout>
|