編輯:關於 Android 程式設計
上一篇談的是導航欄「下方」的滑動切換,這次要處理的是導航欄「上方」的分類切換:點一下頂部的分類標籤,下面的列表就換成對應資料。這種互動在通訊錄、訂單中心、分類瀏覽頁裡幾乎是標配,但實作成本並不高。

整個頁面可以拆成三層:頂部自訂的標題欄 frameHead、中間的分類切換區、下方的搜尋框與 ListView。關鍵在於切換區使用的 RadioGroup(id 為 contentLayout),它才是承載所有分類按鈕的父容器。
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/tab3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/color_white">
<!-- 自訂標題欄 -->
<RelativeLayout
android:id="@+id/frameHead"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<!-- 返回鍵 -->
<RelativeLayout
android:id="@+id/returnBtn"
android:layout_width="50dp"
android:layout_height="fill_parent"
android:background="@drawable/btn_right">
<ImageView
android:id="@+id/returnBtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/btn_back_new"
android:duplicateParentState="true" />
</RelativeLayout>
<!-- 標題文字 -->
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ellipsize="end"
android:singleLine="true" />
<!-- 分類切換區:RadioGroup -->
<RadioGroup
android:id="@+id/contentLayout"
android:layout_width="wrap_content"
android:layout_height="28dp"
android:layout_centerInParent="true"
android:background="@drawable/address_class_tab_bg"
android:orientation="horizontal" />
</RelativeLayout>
<!-- 搜尋框 -->
<LinearLayout
android:id="@+id/searchLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/frameHead"
android:background="@color/color_search_bg"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<EditText
android:id="@+id/keySearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/search_back_new" />
<TextView
android:id="@+id/clearSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="@string/qu_xiao"
android:textColor="@color/color_9b9b9b"
android:textSize="16sp"
android:visibility="gone" />
</LinearLayout>
<!-- 資料列表 -->
<ListView
android:id="@+id/addressListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/searchLayout"
android:cacheColorHint="#00000000"
android:divider="@null"
android:listSelector="@drawable/listitem_selector"
android:scrollbars="none" />
</RelativeLayout>
這裡刻意把原專案裡一堆與主題無關的節點(頭像橫滑列、遮罩層、空資料提示等)拿掉了,只留下切換相關的骨架。實際專案中這些節點照舊保留即可,不影響切換邏輯。
進入頁面時,先把第一個分類的資料灌給 Adapter,讓使用者看到的永遠是「選中第一個分類」的狀態。
/**
* 初始化列表資料與 Adapter
*/
private void setAdapter() {
if (!Validators.isEmpty(typeList)) {
// 預設取第一個分類
getBaseMenuDtoList(typeList.get(0).getUserList());
} else {
getBaseMenuDtoList(new ArrayList<EtoHUser>());
}
getTab(typeList); // 動態產生頂部分類按鈕
setSelector(0); // 預設選中第 0 個
addressAdapter = new AddressClassAdapter(
AddressBookClassActivity.this,
baseMenuDtoList,
getLoginedUser().getUserId());
addressListView.setAdapter(addressAdapter);
}
getBaseMenuDtoList() 負責把後端回傳的原始結構轉換成 Adapter 需要的 DTO 清單,並更新 baseMenuDtoList 這個成員變數。切換的整套效果,其實就是靠 getTab() 與 setSelector() 這兩行撐起來的。
/**
* 依分類清單動態產生切換頁
*/
private void getTab(final List<UserType> typeList) {
roleChangeArea.removeAllViews();
for (int i = 0; i < typeList.size(); i++) {
RadioButton radioButton = (RadioButton) LayoutInflater
.from(this)
.inflate(R.layout.address_class_tab_item, null);
radioButton.setText(typeList.get(i).getOwnerName());
// 頭、中、尾三種背景,拼出連體的分段樣式
if (i == 0) {
radioButton.setBackgroundDrawable(DrawableUtils.getLeftTabDrawable(this));
} else if (i == typeList.size() - 1) {
radioButton.setBackgroundDrawable(DrawableUtils.getRightTabDrawable(this));
} else {
radioButton.setBackgroundDrawable(DrawableUtils.getCenterTabDrawable(this));
}
roleChangeArea.addView(radioButton);
final int id = i;
radioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setSelector(id);
// 切換分類時,若搜尋框有內容則沿用搜尋結果,否則刷新列表
String word = keySearch.getEditableText().toString().trim();
if (TextUtils.isEmpty(word)) {
addressAdapter.notifyDataSetChanged(baseMenuDtoList);
} else {
doSearch(word);
}
}
});
}
}
這裡有兩個值得留意的細節:
第一,roleChangeArea 就是佈局裡的 RadioGroup,透過 removeAllViews() 加上迴圈 addView(),按鈕數量完全由 typeList.size() 決定,後端加一個分類,前端不用改任何程式碼。
第二,頭、中、尾分別套用不同的背景 Drawable,才能拼出「左圓角 + 中段 + 右圓角」的連體分段控件(segmented control)視覺。
每個按鈕的樣板相當樸素:
<RadioButton
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="60dp"
android:layout_height="match_parent"
android:button="@null"
android:gravity="center"
android:includeFontPadding="false"
android:paddingBottom="8dp"
android:paddingLeft="18dp"
android:paddingRight="18dp"
android:paddingTop="8dp"
android:textColor="@color/address_class_tab"
android:textSize="12sp" />
android:button="@null" 拿掉了 RadioButton 預設的小圓點,讓它看起來就是一個普通的分段按鈕。
一般做法是寫一個 res/drawable/xxx.xml,用 <selector> 描述 checked / unchecked 兩種狀態。這裡換成純程式碼寫法,好處是背景可以帶參數、可以依位置動態產生,不必為每種組合準備一個 XML。
public static Drawable getLeftTabDrawable(Context context) {
StateListDrawable drawable = new StateListDrawable();
// 未選中:透明,露出父容器 RadioGroup 的底色
drawable.addState(new int[]{-android.R.attr.state_checked},
context.getResources().getDrawable(R.color.color_transparent));
// 選中:左段高亮圖
drawable.addState(new int[]{android.R.attr.state_checked},
context.getResources().getDrawable(R.drawable.address_class_tab_bg_left_checked));
return drawable;
}
getCenterTabDrawable() 與 getRightTabDrawable() 結構完全相同,只是選中態換成中段與右段的 nine-patch 圖。順帶一提,StateListDrawable.addState() 是「先符合者勝」,所以狀態陣列的排列順序會直接影響結果,這點和 XML selector 的規則一致。
/**
* 設定選中效果並載入對應分類資料
*/
public void setSelector(int id) {
position = id;
RadioButton radioButton = (RadioButton) roleChangeArea.getChildAt(position);
radioButton.setChecked(true);
getBaseMenuDtoList(typeList.get(id).getUserList());
}
這個方法只有三件事,但每一件都缺一不可:
setChecked(true) 觸發 state_checked 變化,由於前面已經替每個按鈕掛上 StateListDrawable,背景會自動切換成高亮態——這就是「不用寫 selector 也能換背景」的原因。
接著 getBaseMenuDtoList(typeList.get(id).getUserList()) 把新分類的資料準備好,寫回 baseMenuDtoList。回到 getTab() 的點擊回呼裡,緊接著的 addressAdapter.notifyDataSetChanged(baseMenuDtoList) 就會把新資料推給列表。
若搜尋框裡還有關鍵字,則改走 doSearch(word),在切換分類的同時把搜尋條件套用到新分類上,避免使用者切換後搜尋結果憑空消失。
整套機制的骨架其實只有三個角色:RadioGroup 負責管理選中態、StateListDrawable 負責把選中態翻譯成視覺、setSelector() 負責把選中態翻譯成資料。理解這三者的分工之後,無論分類是 3 個還是 30 個,程式碼都不用再動。
如果分類數量可能很多,建議再補一個 HorizontalScrollView 包住 RadioGroup,並在 setSelector() 裡呼叫 smoothScrollTo() 讓選中項自動滾進可視範圍,體驗會好很多。
Android Studio 0.5.2 菜單鍵崩潰問題排查與 Gradle 降級方案
問題現象 在 Android Studio 0.5.2 中,部分專案會出現點擊 Menu 鍵導致應用程式崩潰的問題。這類問題可能與 Gradle 外掛版本不相容有關。
Android 優化:殺死使用者選取的進程後即時刷新 ListView
在前一篇《殺死使用者選取的進程(釋放進程占用的空間)》中,我介紹了如何殺死選取的進程,但遺留一個問題:殺死進程後 ListView 沒有立即刷新。本篇就來解決這個問題,優
Android 中 JSON 資料的讀取與建立實作
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,可讀性高、撰寫方便,主流語言都有完整的支援,因此成為跨平台資料交換的常見選擇。
【Android】掌握自定義 LayoutManager:打造 RecyclerView 流式布局
自定義 LayoutManager 實作流式布局 流式布局看似簡單,但若要支援滑動、回收與不同寬度的 Item,難度會明顯提升。本文以垂直滾動的 RecyclerView