<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.progressbar.MainActivity$PlaceholderFragment" > <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 定义一个大环形进度条 --> <ProgressBar style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 定义一个普通环形进度条 --> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 定义一个小环形进度条 --> <ProgressBar style="?android:attr/progressBarStyleSmall" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/progress" /> <!-- 水平进度条 --> <ProgressBar android:id="@+id/bar1" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="100" /> <!-- 自定义水平进度条 --> <ProgressBar android:id="@+id/bar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:progressDrawable="@drawable/my_bar" android:max="100" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <!-- 定义轨道背景 --> <item android:id="@android:id/background" android:drawable="@drawable/no"></item> <item android:id="@android:id/progress" android:drawable="@drawable/ok"></item> </layer-list>
package com.example.progressbar; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ProgressBar; public class MainActivity extends Activity { private int[] data=new int[100]; int hasData=0; //记录完成进度 int status=0; ProgressBar bar,bar1; //創建一个负责更新进度的handler Handler mhandler=new Handler(){ public void handleMessage(Message msg) { if(msg.what==0x111){ bar.setProgress(status); bar1.setProgress(status); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bar=(ProgressBar) findViewById(R.id.bar); bar1=(ProgressBar) findViewById(R.id.bar1); new Thread(){ public void run(){ while(status<100){ //获取耗时操作的完成百分比 status=doWork(); //发送消息 mhandler.sendEmptyMessage(0x111); } } }.start(); } public int doWork() { data[hasData++]=(int) (Math.random()*100); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return hasData; } }
只里面用到了线程,handler的知识。