編輯:關於 Android 程式設計
ProgressBar 是使用者回饋設計裡最基礎的元件。它主要分成兩種形態:旋轉式( indeterminate,適合不確定耗時的載入)與水平式( determinate,適合已知总量的任務)。樣式可以完全自訂,本文從最簡單的點擊演示一路寫到「讀檔進度即時反映」的實用案例。
網上大量範例都是「按一下按鈕,進度加一點」,用的方法是 incrementProgressBy(int)。先來看最精簡的版本:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cn.teachcourse.www.MainActivity"
android:orientation="vertical"
android:gravity="center"
android:id="@+id/onclick_ll">
<!-- 點擊 LinearLayout,改變 ProgressBar 進度 -->
<ProgressBar
android:id="@+id/progressBar_horizontal"
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_marginTop="28dp"/>
</LinearLayout>
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private ProgressBar pb_horizontal;
private LinearLayout onclick_ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
// 套用自定義的水平進度條樣式
Drawable drawable = getResources().getDrawable(R.drawable.progress_bar_states);
pb_horizontal.setProgressDrawable(drawable);
pb_horizontal.setMax(100); // 設定進度上限
onclick_ll.setOnClickListener(this); // 為容器掛上監聽器
}
private void initView() {
pb_horizontal = (ProgressBar) findViewById(R.id.progressBar_horizontal);
onclick_ll = (LinearLayout) findViewById(R.id.onclick_ll);
}
@Override
public void onClick(View v) {
pb_horizontal.incrementProgressBy(5);
if (pb_horizontal.getProgress() == pb_horizontal.getMax()) {
Toast.makeText(this, "進度條已達最大值,進度歸零", Toast.LENGTH_LONG).show();
pb_horizontal.setProgress(0);
}
}
}
這段程式只是為了說明 API 怎麼用。真實專案裡,進度值幾乎不可能來自使用者點擊——它來自某個正在背景進行的任務。
效果如下圖,進度條會隨著讀檔位置同步推進,讀完剛好填滿:
效果圖:ProgressBar 讀取檔案位元組流演示

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cn.teachcourse.www.MainActivity"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/read_data_tv"
android:text="@string/read_info"
android:scrollbars="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:lineSpacingExtra="10dp"/>
<ProgressBar
android:id="@+id/progressBar_horizontal_read_data"
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_marginTop="28dp"/>
</LinearLayout>
public class ProgressBarActivity extends ActionBarActivity {
private ProgressBar pb_horizontal;
private int readed; // 每次實際讀到的位元組數
private int progressValue; // 累計已讀位元組數
private TextView mReadProgress_TV;
private String mData;
private StringBuffer sb; // 已讀內容
private int length; // 檔案總大小
private Thread thread; // 讀檔執行緒
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_horizontal_read_data);
initView();
Drawable drawable = getResources().getDrawable(R.drawable.progress_bar_states);
String path = Environment.getExternalStorageDirectory() + "/ProgressMonitor.txt";
final File file = new File(path);
if (file.exists()) {
length = (int) file.length();
pb_horizontal.setMax(length); // 以「總位元組數」為上限
pb_horizontal.setProgressDrawable(drawable);
}
thread = new Thread() {
@Override
public void run() {
readFromFile(file.getAbsolutePath());
}
};
thread.start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 110:
progressValue += msg.arg1; // arg1 帶回本次讀到的位元組數
pb_horizontal.setProgress(progressValue);
mReadProgress_TV.setText(sb.toString());
if (progressValue == length) {
Toast.makeText(ProgressBarActivity.this, "檔案讀取完成", Toast.LENGTH_LONG).show();
}
Log.d("progressValue-------------->", progressValue + "");
break;
}
}
};
public void readFromFile(String path) {
FileInputStream fis;
try {
fis = new FileInputStream(path);
DataInputStream dis = new DataInputStream(fis);
sb = new StringBuffer();
byte b[] = new byte[10]; // 每次讀 10 個位元組,實務上可調大以提升效能
while ((readed = dis.read(b)) != -1) {
Message msg = new Message();
msg.arg1 = readed;
msg.what = 110;
mData = new String(b, 0, readed);
sb.append(mData);
handler.sendMessage(msg);
try {
Thread.sleep(1000); // 刻意放慢,方便觀察進度變化
} catch (Exception e) {
e.printStackTrace();
}
}
dis.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initView() {
pb_horizontal = (ProgressBar) findViewById(R.id.progressBar_horizontal_read_data);
mReadProgress_TV = (TextView) findViewById(R.id.read_data_tv);
}
}
setMax(length) 之所以能運作,是因為上限與累加值都用「位元組」當單位。如果換成下載任務,就該改用 Content-Length;如果是未知大小的串流,則只能退回旋轉式進度條。
讀檔在子執行緒跑,UI 更新交給 Handler。範例用 Message.arg1 攜帶本次讀到的位元組數,這是 Message 的推薦用法——比 obj 效率更好,也不會產生不必要的物件。
把「讀本機檔案」換成「下載網路檔案」或「上傳資料」,同樣的骨架完全適用:只需把「每次讀到的位元組數」替換成「每次寫出的位元組數」,並以總傳輸量為上限即可。
NetworkOnMainThreadException 或直接 ANR。/sdcard 需要 READ/WRITE_EXTERNAL_STORAGE 或 Scoped Storage 對應做法,記得處理執行期權限。Thread.sleep(1000) 只是為了讓動畫看得清楚,正式環境請移除。以上就是本文的全部內容,希望對你的 Android 程式設計有所幫助。
Android Native 反調試方式及使用 IDA 繞過反調試的實戰
0x00 為了避免我們的 so 文件被動態分析,通常會在 so 中加入一些反調試代碼。常見的 Android native 反調試方法有以下幾種: 1、直接調用 ptra
Android 使用 RecyclerView 與 CardView 實現瀑布流效果
RecyclerView 與瀑布流 Android 5.0 引入 Material Design 後,RecyclerView 與 CardView 成為打造現代化列表的
小米手機助手怎麼刷機?用電腦端完成系統升級的步驟
手機賣得好,順手做一個手機助手,說是工具不如說是給使用者的福利。vivo 有 vivo 手機助手,小米則有小助手。它能做的事不少,其中最多人問的就是:能不能用它刷機?答案
Android 高斯模糊實戰:基於 Bitmap 的高效模糊工具類封裝
圖片模糊是常見需求,做過 iOS 或前端的同學大概都接觸過毛玻璃效果。網上 Android 的實現不少,但很多方案要麼效果不理想,要麼性能開銷大。這裡分享一個項目中實際用