本文實例講述了Android控件之ProgressBar用法。分享給大家供大家參考。具體如下:
ProgressBar位于android.widget包下,其繼承于View,主要用于顯示一些操作的進度。應用程序可以修改其長度表示當前后臺操作的完成情況。因為進度條會移動,所以長時間加載某些資源或者執行某些耗時的操作時,不會使用戶界面失去響應。ProgressBar類的使用非常簡單,只需將其顯示到前臺,然后啟動一個后臺線程定時更改表示進度的數值即可。
以下ProgressBar跟Handle結合,模擬進度條的使用,當進度條完成時會跳轉到TestActivity
main.xml布局文件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <!-- 長方形進度條,一開始不可見,直到點擊按鈕時才出現進度條 --> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" mce_style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:visibility="gone" android:max="100" /> <!-- 圓形進度條 --> <!--<ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleLarge" mce_style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" />--> <Button android:id="@+id/start" android:text="啟動進度條" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/stop" android:text="停止進度條" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout>
PbActivity類
package com.ljq.pb;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;public class PbActivity extends Activity { private ProgressBar progressBar = null; private Button start = null, stop = null; // 定義Handler對象 private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setProgress(0); start = (Button) findViewById(R.id.start); start.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handler.post(runnable); //開始執行 } }); stop=(Button)findViewById(R.id.stop); stop.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handler.removeCallbacks(runnable);//停止執行 progressBar.setProgress(0); } }); } int pro=0; Runnable runnable=new Runnable(){ public void run() { progressBar.setVisibility(View.VISIBLE); pro=progressBar.getProgress()+10; progressBar.setProgress(pro); //如果進度小于100,,則延遲1000毫秒后重復執行runnable if(pro<100){ handler.postDelayed(runnable, 1000); }else{ progressBar.setVisibility(View.GONE); startActivity(new Intent(PbActivity.this, TestActivity.class)); handler.removeCallbacks(runnable); progressBar.setProgress(0); } } };}
運行結果
希望本文所述對大家的Android程序設計有所幫助。
新聞熱點
疑難解答
圖片精選