編輯:初階開發
本篇繼續整理 ApiDemo「Graphics and Views」第 58 到 69 號範例,主題集中在兩塊:一是 ListView 的選擇模式與高效 Adapter 寫法,二是進度呈現的各種形式——橫向進度條、標題欄進度、ProgressDialog、RatingBar 與 SeekBar。
與單選版本相比,只差兩處:行布局換成 simple_list_item_multiple_choice,choiceMode 改為 CHOICE_MODE_MULTIPLE。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView(); // 取得目前的 List
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
第 8 行的 getListView() 是 ListActivity 提供的便捷方法,等同於 findViewById(android.R.id.list),但更短也更安全。
這個範例解決的是一個非常常見的痛點:底部輸入框一聚焦就被模擬器/裝置的輸入法蓋住。布局由「列表 + EditText」組成,靠兩個屬性同時達到「列表由下往上長」與「自動捲到底」的效果。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="8dip"
android:paddingRight="8dip">
<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:stackFromBottom="true"
android:transcriptMode="normal" />
<EditText android:id="@+id/userText"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
兩個屬性的分工:
android:stackFromBottom="true":讓清單內容從底部開始堆疊,模擬聊天室「新訊息在下方」的視覺慣例。android:transcriptMode="normal":當有新資料加入時,若使用者本來就在底部,清單會自動滑到最新一筆;若使用者正在往上翻閱歷史紀錄,則不會被打斷。這個細節對聊天類應用至關重要。程式端最值得注意的是第 24 行——直接把新字串加進 ArrayAdapter,Adapter 會自行處理資料與通知:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_12);
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mStrings);
setListAdapter(mAdapter);
mUserText = (EditText) findViewById(R.id.userText);
mUserText.setOnClickListener(this);
mUserText.setOnKeyListener(this);
}
public void onClick(View v) {
sendText();
}
private void sendText() {
String text = mUserText.getText().toString();
mAdapter.add(text);
mUserText.setText(null);
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
sendText();
return true;
}
}
return false;
}
這裡用 OnKeyListener 攔下實體鍵盤與方向鍵中心的 Enter,模擬「送出」。在真實專案中,若要處理 IME 的送出動作,更準確的做法是為 EditText 設定 imeOptions 搭配 setOnEditorActionListener,因為軟鍵盤的 Enter 未必會走 onKey 流程。
這個範例在 ApiDemo 裡是「高效列表」的教科書。它示範了三個至今仍在使用的最佳實踐:快取 LayoutInflater、複用 convertView、以 ViewHolder 暫存子視圖引用。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new EfficientAdapter(this));
}
第一,在 Adapter 建構時就把 LayoutInflater 與圖示快取起來,避免每次 getView 都重新解碼資源:
public EfficientAdapter(Context context) {
// Cache the LayoutInflater to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
// Icons bound to the rows.
mIcon1 = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon48x48_2);
}
第二,用一個小小的 ViewHolder 類持有子視圖引用:
static class ViewHolder {
TextView text;
ImageView icon;
}
第三,getView 中的分流邏輯。當 convertView 為 null 才 inflate 並建立 holder,否則直接從 tag 取回:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// convertView 不為 null 時可直接重用,不需重新 inflate
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
return convertView;
}
為什麼要這樣做?因為 findViewById() 是一次完整的視圖樹走訪,成本不低。 ListView 在滾動時會以每秒數十次的頻率呼叫 getView,如果每次都對每一列跑好幾次 findViewById,掉幀幾乎是必然的。用 setTag() 把查好的引用掛在 convertView 上,第二次之後就是 O(1) 的取用。
最後那個 (position & 1) == 1 是位元運算版的奇偶判斷,等價於 position % 2 == 1,效果是讓兩種圖示在列之間交錯出現,方便肉眼確認每列的資料確實有被正確重新綁定。
布局中的橫向進度條需要三個關鍵屬性:style 決定外觀、max 決定上限、progress 與 secondaryProgress 決定初始值。
<ProgressBar android:id="@+id/progress_horizontal"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:secondaryProgress="75" />
程式端有一個非常容易被忽略的細節:標題欄的進度範圍是 0 到 10000,而不是 0 到 100。所以同步時必須乘以 100。
// Request the progress bar to be shown in the title requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.progressbar_1); setProgressBarVisibility(true); final ProgressBar progressHorizontal = (ProgressBar) findViewById(R.id.progress_horizontal); // 少了這兩句,標題欄不會顯示進度;注意必須乘以 100 setProgress(progressHorizontal.getProgress() * 100); setSecondaryProgress(progressHorizontal.getSecondaryProgress() * 100);
另一個實用方法是 incrementProgressBy() 與 incrementSecondaryProgressBy():傳正數為加、傳負數為減,省去自己計算差值。
Button button = (Button) findViewById(R.id.increase);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
progressHorizontal.incrementProgressBy(1);
setProgress(100 * progressHorizontal.getProgress());
}
});
button = (Button) findViewById(R.id.decrease_secondary);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
progressHorizontal.incrementSecondaryProgressBy(-1);
setSecondaryProgress(100 * progressHorizontal.getSecondaryProgress());
}
});
補充一個觀念:secondaryProgress 常用來表達「緩衝進度」或「第二層基準線」,例如線上影片播放時,第一條代表已播放位置、第二條代表已下載緩衝的位置。
不指定 style 時,ProgressBar 預設就是中等尺寸的旋轉動畫。這裡示範了四種內建樣式:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ProgressBar android:id="@+android:id/progress_large"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar android:id="@+android:id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar android:id="@+android:id/progress_small"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar android:id="@+android:id/progress_small_title"
style="?android:attr/progressBarStyleSmallTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
// 在標題欄顯示不確定型態的進度 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.progressbar_2); setProgressBarVisibility(true);
這裡的 FEATURE_INDETERMINATE_PROGRESS 與前例的 FEATURE_PROGRESS 對應兩種不同語意:前者是「不知道還要多久,但正在忙」,後者是「有明确百分比」。選錯會讓使用者對等待時間產生錯誤預期。
上方按鈕開啟帶標題的對話框,下方按鈕開啟不帶標題的版本。範例使用 showDialog() 搭配 onCreateDialog() 的傳統寫法(Activity 會自行管理Dialog 的生命週期與重複呼叫)。
private static final int DIALOG1_KEY = 0;
private static final int DIALOG2_KEY = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar_3);
Button button = (Button) findViewById(R.id.showIndeterminate);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG1_KEY);
}
});
button = (Button) findViewById(R.id.showIndeterminateNoTitle);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG2_KEY);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG1_KEY: {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Indeterminate");
dialog.setMessage("Please wait while loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
case DIALOG2_KEY: {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Please wait while loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}
兩個版本的差異只在有没有呼叫 setTitle()。而 setIndeterminate(true) 表示這是不確定的等待型進度;若需要顯示百分比,則改為 setProgressStyle(ProgressDialog.STYLE_HORIZONTAL) 並搭配 setMax() 與 setProgress()。setCancelable(true) 則允許使用者按返回鍵關閉對話框。
private boolean mToggleIndeterminate = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 一定要有這一行
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.progressbar_4);
setProgressBarIndeterminateVisibility(mToggleIndeterminate);
Button button = (Button) findViewById(R.id.toggle);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mToggleIndeterminate = !mToggleIndeterminate;
setProgressBarIndeterminateVisibility(mToggleIndeterminate);
}
});
}
requestWindowFeature() 必須在 setContentView() 之前呼叫,這是硬性順序要求;放到後面會直接拋出例外。setProgressBarIndeterminateVisibility() 則負責控制標題欄那個小轉圈圖示的顯示與隱藏。
布局中一個 RadioGroup 內含四個 RadioButton,預設選中項由 android:checkedButton="@+id/lunch" 指定。
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@+id/lunch"
android:id="@+id/menu">
<RadioButton android:text="@string/radio_group_1_breakfast"
android:id="@+id/breakfast" />
<RadioButton android:text="@string/radio_group_1_lunch"
android:id="@id/lunch" />
<RadioButton android:text="@string/radio_group_1_dinner"
android:id="@+id/dinner" />
<RadioButton android:text="@string/radio_group_1_all"
android:id="@+id/all" />
<TextView android:text="@string/radio_group_1_selection"
android:id="@+id/choice" />
</RadioGroup>
程式端示範了三件事:動態新增 RadioButton、監聽選擇變化、以及清空選擇。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio_group_1);
mRadioGroup = (RadioGroup) findViewById(R.id.menu);
// 以程式碼動態加入一個 RadioButton
RadioButton newRadioButton = new RadioButton(this);
newRadioButton.setText(R.string.radio_group_snack);
newRadioButton.setId(R.id.snack);
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
mRadioGroup.addView(newRadioButton, 0, layoutParams);
// 監聽選擇變更
String selection = getString(R.string.radio_group_selection);
mRadioGroup.setOnCheckedChangeListener(this);
mChoice = (TextView) findViewById(R.id.choice);
mChoice.setText(selection + mRadioGroup.getCheckedRadioButtonId());
// 清空選擇
Button clearButton = (Button) findViewById(R.id.clear);
clearButton.setOnClickListener(this);
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
String selection = getString(R.string.radio_group_selection);
String none = getString(R.string.radio_group_none);
mChoice.setText(selection
+ (checkedId == View.NO_ID ? none : checkedId));
}
public void onClick(View v) {
mRadioGroup.clearCheck();
}
兩個實務提醒:addView(child, 0, params) 的第二個參數是插入位置,傳 0 會插到最前面;另外 RadioGroup 內只能放 RadioButton 才會被納入同一組互斥管理,其他元件(如範例中的 TextView)不受影響。
布局中有四個 RatingBar,分別示範預設樣式、小尺寸樣式與僅供顯示的 indicator 樣式。
<RatingBar android:id="@+id/ratingbar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="3"
android:rating="2.5" />
<RatingBar android:id="@+id/ratingbar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:rating="2.25" />
<RatingBar android:id="@+id/small_ratingbar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
<RatingBar android:id="@+id/indicator_ratingbar"
style="?android:attr/ratingBarStyleIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
重點屬性:android:numStars 是星星總數,android:rating 是初始評分。ratingBarStyleSmall 縮小尺寸,ratingBarStyleIndicator 則是純展示用的樣式——它不會回應觸控,適合當作「唯讀的結果呈現」。
程式端的設計是:讓兩個 indicator 星條永遠跟隨使用者最近一次調整的數值。
// 這兩個 RatingBar 用來同步顯示最近變更的分數
mIndicatorRatingBar = (RatingBar) findViewById(R.id.indicator_ratingbar);
mSmallRatingBar = (RatingBar) findViewById(R.id.small_ratingbar);
((RatingBar) findViewById(R.id.ratingbar1))
.setOnRatingBarChangeListener(this);
((RatingBar) findViewById(R.id.ratingbar2))
.setOnRatingBarChangeListener(this);
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
final int numStars = ratingBar.getNumStars();
mRatingText.setText(getString(R.string.ratingbar_rating) + " "
+ rating + "/" + numStars);
// 星數不同時要一併更新,否則比例會失真
if (mIndicatorRatingBar.getNumStars() != numStars) {
mIndicatorRatingBar.setNumStars(numStars);
mSmallRatingBar.setNumStars(numStars);
}
if (mIndicatorRatingBar.getRating() != rating) {
mIndicatorRatingBar.setRating(rating);
mSmallRatingBar.setRating(rating);
}
final float ratingBarStepSize = ratingBar.getStepSize();
if (mIndicatorRatingBar.getStepSize() != ratingBarStepSize) {
mIndicatorRatingBar.setStepSize(ratingBarStepSize);
mSmallRatingBar.setStepSize(ratingBarStepSize);
}
}
這裡有一個容易忽略的重點:同步 rating 之前必須先同步 numStars。因為 3 星滿分下的 2.5 與 5 星滿分下的 2.5,視覺意義完全不同。程式中先比對 numStars 再比對 rating,順序是有意設計的。
當 ratingBar 為三顆星時的呈現。
當 ratingBar 為五顆星時的呈現。
什麼都不設定時,當內容超出畫面,系統會自動顯示預設樣式的垂直 scrollbar。
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/scrollbar_1_text" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/scrollbar_1_text" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/scrollbar_1_text" />
</LinearLayout>
</ScrollView>
與前例唯一的不同在於外觀,靠三個屬性達成:
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbarTrackVertical="@drawable/scrollbar_vertical_track"
android:scrollbarThumbVertical="@drawable/scrollbar_vertical_thumb"
android:scrollbarSize="12dip">
...
</ScrollView>
scrollbarTrackVertical 是軌道(背景槽),scrollbarThumbVertical 是可拖曳的滑桿,scrollbarSize 決定寬度。兩者都是標準的 shape drawable:
res/drawable/scrollbar_vertical_track.xml:
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<gradient android:startColor="#505050" android:endColor="#C0C0C0"
android:angle="0"/>
<corners android:radius="0dp" />
</shape>
res/drawable/scrollbar_vertical_thumb.xml:
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<gradient android:startColor="#3333FF" android:endColor="#8080FF"
android:angle="0"/>
<corners android:radius="6dp" />
</shape>
差別只在顏色與圓角:軌道是灰階、無圓角;滑桿是藍色漸層、6dp 圓角。這示範了「不用一張圖片,純 XML 就能做出可複用的控制項外觀」。
這個範例把四個 ScrollView 並排,用不同背景色區隔,方便直接比較 scrollbar 的呈放位置差異。
程式端示範用 Java 設定 style:
setContentView(R.layout.scrollbar3); findViewById(R.id.view3).setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
XML 端則可對另外兩個 ScrollView 直接宣告:
<ScrollView android:id="@+id/view4"
android:layout_width="100dip"
android:layout_height="120dip"
android:scrollbarStyle="outsideOverlay"
android:background="@android:drawable/edit_text">
...
</ScrollView>
<ScrollView android:id="@+id/view5"
android:layout_width="100dip"
android:layout_height="120dip"
android:scrollbarStyle="outsideInset"
android:background="@android:drawable/edit_text">
...
</ScrollView>
四種值的語意整理如下:
insideOverlay(預設):scrollbar 疊在內容之上,位於 padding 內側。insideInset:scrollbar 位於 padding 內側,但會額外留出空間,不覆蓋內容。outsideOverlay:scrollbar 畫在 padding 之外,同樣以覆疊方式呈現。outsideInset:scrollbar 畫在 padding 之外並另外留白。實務上的選擇依據很簡單:如果內容是文字、不希望被遮擋,選 inset 系列;如果元件本身已有足夠內距、想要視覺更精簡,選 overlay 系列。
SeekBar 繼承自 ProgressBar,因此 max/progress/secondaryProgress 這組屬性完全通用,差別在於它多了觸控互動與三個回呼。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SeekBar android:id="@+id/seek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:secondaryProgress="75" />
<TextView android:id="@+id/progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="@+id/tracking"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
SeekBar mSeekBar;
TextView mProgressText;
TextView mTrackingText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seekbar_1);
mSeekBar = (SeekBar) findViewById(R.id.seek);
mSeekBar.setOnSeekBarChangeListener(this);
mProgressText = (TextView) findViewById(R.id.progress);
mTrackingText = (TextView) findViewById(R.id.tracking);
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
mProgressText.setText(progress + " "
+ getString(R.string.seekbar_from_touch) + "=" + fromTouch);
}
public void onStartTrackingTouch(SeekBar seekBar) {
mTrackingText.setText(getString(R.string.seekbar_tracking_on));
}
public void onStopTrackingTouch(SeekBar seekBar) {
mTrackingText.setText(getString(R.string.seekbar_tracking_off));
}
三個回呼各有用途,而 fromTouch 參數特別值得留意:它用來區分「這次變化是使用者手動拖曳」還是「程式呼叫 setProgress() 造成的」。在實務上,若想避免程式回寫時觸發無限迴圈或冗餘運算,就靠這個旗標來過濾。
而 onStartTrackingTouch/onStopTrackingTouch 則是效能與體驗的關鍵:拖曳期間可能一秒觸發數十次 onProgressChanged,聰明的做法是在 startTracking 時暫停昂貴運算(例如停止解碼媒體),在 stopTracking 時才提交一次完整處理。影音播放器的時間軸就是這個模式的典型應用。
這一段的兩條主線其實指向同一件事:使用者等待時的體驗,以及列表滾動時的流暢度。ProgressDialog、標題欄進度、SeekBar 的 tracking 回呼,都是在處理「等待」;而 ViewHolder、convertView 複用、transcriptMode,則是在處理「滑動」。
如果要挑一個最該帶進真實專案的技巧,我會選 EfficientAdapter 的 ViewHolder 模式——它成本極低、效果立竿見影,而且直到今日在 RecyclerView 時代仍然以 onCreateViewHolder/onBindViewHolder 的形式被內建實作。
Android IPC 框架分析:Binder、Service 與 Service Manager
宏觀角度 在 Android 中,Activity 與 Service 可能託管於不同行程。不同行程之間若要交換資料,就屬於 IPC。Binder 是 Android 為
Android Socket 編程:非阻擋 I/O 伺服器與 Service 範例
改良目標 傳統 Socket 聊天範例常有兩個問題:伺服器在等待連線時容易造成 I/O 阻擋;伺服器端也缺少使用者列表,無法將訊息廣播給所有已連線的客戶端。因此可改用非阻
用 Android 手機遠端控制電腦
想在被窩裡使用電腦,卻不想離開溫暖的床?透過遠端桌面,Android 手機也能成為控制電腦的終端裝置。只要電腦與手機連上同一網路,就能在手機上操作 Windows 桌面。
行動 Web 開發者值得收藏的 9 個框架與工具
行動開發的熱潮從 iPhone 起算,行動瀏覽器對 HTML5、CSS3 與 CSS 動畫的支持也快速成熟;Google 推出 Android 之後,行動平台時代正式成形