Android 实现一个简单加载进度条的功能
1、布局页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 进度条-->
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pb_progressbar_bar" />
<!--数字1-100%-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_progressbar_num"
/>
<!--开始下载点击按钮-->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"
android:onClick="download"
/>
</LinearLayout>
2、再实现方法
public class ProgressAtivity extends AppCompatActivity { private ProgressBar pb_progressbar_bar; private TextView tv_progressbar_num; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.progressbar); // 进度条 pb_progressbar_bar = (ProgressBar) findViewById(R.id.pb_progressbar_bar); tv_progressbar_num = (TextView) findViewById(R.id.tv_progressbar_num); } /** * ANR * application not responsing 应用程序未响应 * why:在主线程中执行了耗时的操作 * how:在子线程中执行耗时操作 */ public void download(View view) {
new Mythread().start();
} Handler handler = new Handler() {
//接受消息,更新UI界面
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int i = msg.what;
tv_progressbar_num.setText(i + "");
}
};
/*CalledFromWoringThreadException从错误的线程中调用错误*/
class MyThread extends Thread{
@Override
public void run() {
super.run();
for (int i = 0; i <=100; i++) {
pb_progressbar_bar.setProgress(i);
//在子线程中发消息
handler.sendEmptyMessage(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
3、最后还需配置
省