直线进度条效果图:
点击下载后的效果图:
布局xml文件:
empty
Java代码:
package com.example.android_rogressbar;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ProgressBar pb_progress_bar;
private TextView tv_main_text;
private ImageView iv_main_image;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//根据ID获取控件 pb_progress_bar = (ProgressBar) findViewById(R.id.pb_progress_bar);
tv_main_text = (TextView) findViewById(R.id.tv_main_text);
}
//下载的方法 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_main_text.setText(i+"");
}
}
;
class MyThread extends Thread{
@Override public void run() {
super.run();
for (int i = 0;
i <= 100;
i++) {
pb_progress_bar.setProgress(i);
//在子线程中发送消息 handler.sendEmptyMessage(i);
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
ProgressBar.java
<?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" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.android_rogressbar.MainActivity"> <!--style:设置进度条的样式,这里为直线进度条--> <ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/pb_progress_bar" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_main_text" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载" android:onClick="download" /></LinearLayout>
因为主线程执行耗时代码会报错,所以我们新建一个子线程来执行进度条
在子程序中我们没办法对控件进行操作,所以我们需要用到handler类,实现主线程和子线程之间的通信;
Handler的定义
主要接受子线程发送的数据,并用此数据配合主线程更新UI。
当应用程序启动时,Android首先会开启一个主线程 (即UI线程),主线程管理界面中的UI控件,进行事件分发,比如说:点击Button,Android系统会分发事件到Button上,来响应你的操作。如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,如果你放在主线程中的话,界面会出现假死现象,如果5秒钟还没有完成的话,会收到Android系统的一个错误提示“强制关闭”。这个时候我们需要把这些耗时的操作,放在一个子线程中。
因为子线程涉及到UI更新,Android主线程是线程不安全的,也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。这个时候,Handler就出现了。来解决这个复杂的问题,由于Handler运行在主线程中(UI线程中), 它与子线程可以通过Message对象来传递数据,这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传递Message对象,(里面包含数据),把这些消息放入主线程队列中,配合主线程进行更新UI。
以上所述是小编给大家介绍的Android ProgressBar直线进度条的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!