ProgressBar进度条
程序员文章站
2022-03-30 16:29:21
...
效果图:
实现代码:
XML代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_progress_num"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"
android:onClick="download"/>
</LinearLayout>
Java代码
public class ProgressActivity extends AppCompatActivity {
private TextView tv_progress_num;
private ProgressBar progressBar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
tv_progress_num = (TextView) findViewById(R.id.tv_progress_num);
}
/**
* ANR
* application not responsing 应用程序未响应
* why:在主线程中执行了耗时的操作
* how:在子线程中执行耗时操作
* @param view
*/
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_progress_num.setText(i+"");
}
};
class MyThread extends Thread{
@Override
public void run() {
super.run();
for (int i = 0; i <=100 ; i++) {
progressBar.setProgress(i);
//在子线程中发消息
handler.sendEmptyMessage(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
上一篇: Windows 下如何运行jar文件程序
下一篇: Flash进度条ProgressBar