ProgressBar用於向用戶顯示某個耗時操作完成的百分比,避免長時間執行某個耗時操作時讓用戶感覺程序失去了響應,從而提高用戶界面的友好性。
請看下面的界面布局:
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Large"
/>
<ProgressBar
android:id="@+id/bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:max="100"
style="@android:style/Widget.ProgressBar.Horizontal"
/>
</LinearLayout>
上面的界面布局定義了2個ProgressBar組件,第1個為大環形,其style屬性為@android:style/Widget.ProgressBar.Large,這種環形進度條默認無法顯示進度,只是顯示一個不斷旋轉的圖片(顯示進度的環形進度條可以參考園子里的
環形進度條實現http://www.cnblogs.com/kimmy/p/4833321.html。)
第2個水平進度條,其style屬性為@android:style/Widget.ProgressBar.Horizontal,該進度條的最大值為100。
接下來用一個填充數組的任務模擬耗時操作,用進度條來標識任務的完成百分比。
public class MainActivity extends Activity { private int[] data=new int[100]; int hasData=0; int status=0; ProgressBar bar; Handler handler=new Handler() { @Override public void handleMessage(Message msg) { if(msg.what==0x11) { bar.setProgress(status); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bar=(ProgressBar)findViewById(R.id.bar); new Thread() { @Override public void run() { // TODO Auto-generated method stub while (status<100) { status=doWork(); handler.sendEmptyMessage(0x11); } } }.start(); } private int doWork() { data[hasData++]=(int)(Math.random()*100); try { Thread.sleep(100); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return hasData; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }