Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 把進度條放進標題欄的實作方式

編輯:關於 Android 程式設計

有時候我們不想為了小小的載入提示而遮擋整個畫面,這時可以借用 Activity 標題欄(Title Bar)內建的進度條,效果如下:

版面配置

版面很單純,一顆顯示鈕、一顆隱藏鈕:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" 顯示"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="隱藏"/> </LinearLayout>

程式碼

關鍵在於:必須在 setContentView() 之前呼叫 requestWindowFeature() 啟用窗口特性,同時具備「不帶進度」與「帶進度」兩種進度條:

 package com.imooc.progressbarr; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; public class MainActivity extends Activity { private Button btn1; private Button btn2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //設置窗口特征:啟用顯示進度的進度條 requestWindowFeature(Window.FEATURE_PROGRESS); //設置窗口特征:啟用不顯示進度的進度條 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_main); Button btn1=(Button)findViewById(R.id.button1); Button btn2=(Button)findViewById(R.id.button2); btn1.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub //顯示不帶進度的進度條 setProgressBarIndeterminateVisibility(true); //顯示不帶進度的進度條 setProgressBarVisibility(true); //設置進度條的進度 setProgress(4500); } }); btn2.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub //隱藏不帶進度的進度條 setProgressBarIndeterminateVisibility(false); //隱藏帶進度的進度條 setProgressBarVisibility(false); } }); } @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; } }

補充兩點實務經驗:setProgress() 的取值上限由 Window 的 progress 屬性決定,預設是 10000,因此範例中的 4500 約為 45%;另外在較新的 Android 版本中,若已改用 Toolbar,標題欄進度條就必須自行以 ProgressBar 控制項實作,這個做法主要適用於傳統 Title Bar 的專案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved