直線進度條效果圖:

點擊下載后的效果圖:

布局xml文件:
empty
Java代碼:
package com.example.android/214812.html">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直線進度條的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答