編輯:關於 Android 程式設計
能讓分組標題懸停在頂部的列表,在實務專案中非常常見——通訊錄的好友分組、地區選擇器、商品分類,幾乎都會用到。本文記錄如何以開源的 PinnedSectionListView 取代原生 ListView,並把分組資料正確餵進去。
先看效果(靜態截圖):

核心思路是:PinnedSectionListView 本身原封不動沿用開源實作,我們要花力氣的是「怎麼把資料適配進去」。
專案結構如下:

Activity 幾乎沒有邏輯,就是建立資料、包裝成 Adapter、掛上去。
public class IndexActivity extends AppCompatActivity {
private PinnedSectionListView pinnedSectionList;
private IndexAdapter indexAdapter;
private List<CityBean> data;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pinnedSectionList = findViewById(R.id.pinned_section_list);
data = new TestData().initData();
indexAdapter = new IndexAdapter(this, data);
pinnedSectionList.setAdapter(indexAdapter);
}
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.android.list.pinnedsectionlistview
android:id="@+id/pinned_section_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@null"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
</RelativeLayout>
分組資料本質上是一棵兩層的樹:上層是城市,下層是它的行政區。
public class CityBean {
private int cityId; // 城市 id
private String cityName; // 城市名
private int superiorId; // 上級城市 id
private List<CityBean> subordinateList; // 下級行政區集合
// getter / setter 省略
}
public class TestData {
public List<CityBean> initData() {
List<CityBean> data = new ArrayList<>();
for (int j = 1; j <= 10; j++) {
// 北京
data.add(buildCity(1, "北京" + j, 10, "北京", "區"));
// 上海
data.add(buildCity(2, "上海" + j, 20, "上海", "區"));
// 深圳
data.add(buildCity(3, "深圳" + j, 20, "深圳", "區"));
}
return data;
}
private CityBean buildCity(int cityId, String name,
int startId, String prefix, String suffix) {
List<CityBean> children = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
CityBean child = new CityBean();
child.setCityId(startId + i);
child.setCityName(prefix + i + suffix);
children.add(child);
}
CityBean parent = new CityBean();
parent.setCityId(cityId);
parent.setCityName(name);
parent.setSubordinateList(children);
return parent;
}
}
Adapter 需要的不是 CityBean,而是一個「告訴列表這一行是標題還是普通項」的包裝物件。
public class Item {
public static final int ITEM = 0; // 普通項目
public static final int SECTION = 1; // 需要懸停的標題項
public final int type; // 型別:ITEM 或 SECTION
public final CityBean cityBean; // 附帶的資料
public int sectionPosition; // 所屬分組的標記,通常用父資料 id
public int listPosition; // 自身在列表中的標記,通常用自身 id
public Item(int type, CityBean cityBean) {
this.type = type;
this.cityBean = cityBean;
}
public CityBean getCityBean() {
return cityBean;
}
}
Item 的作用就是承載外部資料,同時標記它是懸停標題還是普通項目。
懸停列表的 Adapter 必須同時實作兩個接口:
PinnedSectionListView.PinnedSectionListAdapter:告訴控制項哪些 view type 屬於「會被釘住」的標題。SectionIndexer:Android 原生的索引列(A、B、C…)機制,讓使用者可以快速跳段。還有一個容易踩到的坑:PinnedSectionListView 內部會檢查 getViewTypeCount(),若小於 2 會直接拋異常。
public class IndexAdapter extends BaseAdapter
implements PinnedSectionListView.PinnedSectionListAdapter, SectionIndexer {
// 用來區分各分組標題的背景色
private static final int[] COLORS = {
R.color.green_light, R.color.orange_light,
R.color.blue_light, R.color.red_light
};
private final List<CityBean> data; // 外部傳入的原始資料
private List<Item> items; // 真正要顯示的扁平列表
private Item[] sections; // 各分組標題,給 SectionIndexer 用
private final Context context;
public IndexAdapter(Context context, List<CityBean> data) {
this.context = context;
this.data = data;
initSection();
}
/** 把兩層樹狀結構攤平成一維列表,同時建立索引陣列 */
private void initSection() {
items = new ArrayList<>();
sections = new Item[data.size()];
for (int i = 0; i < data.size(); i++) {
CityBean parent = data.get(i);
// 先放標題項
Item section = new Item(Item.SECTION, parent);
section.sectionPosition = parent.getCityId();
section.listPosition = parent.getCityId();
sections[i] = section;
items.add(section);
// 再放該分組底下的普通項
for (CityBean child : parent.getSubordinateList()) {
Item item = new Item(Item.ITEM, child);
item.sectionPosition = parent.getCityId(); // 標明歸屬哪個分組
item.listPosition = child.getCityId();
items.add(item);
}
}
}
/**************** PinnedSectionListAdapter ******************/
@Override
public boolean isItemViewTypePinned(int viewType) {
return viewType == Item.SECTION;
}
/**************** BaseAdapter ******************/
@Override
public int getViewTypeCount() {
return 2; // 少於 2 會讓 PinnedSectionListView 拋異常
}
@Override
public int getItemViewType(int position) {
return getItem(position).type;
}
@Override public int getCount() { return items.size(); }
@Override public Item getItem(int position) { return items.get(position); }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder vh;
View v;
Item item = items.get(position);
if (view == null) {
v = View.inflate(context, R.layout.item, null);
vh = new ViewHolder();
vh.tvName = v.findViewById(R.id.text_text);
v.setTag(vh);
} else {
v = view;
vh = (ViewHolder) view.getTag(); // 複用,避免重複 findViewById
}
vh.tvName.setText(item.getCityBean().getCityName());
if (item.type == Item.SECTION) {
v.setBackgroundColor(parent.getResources()
.getColor(COLORS[item.sectionPosition % COLORS.length]));
}
return v;
}
/** 行內控件的快取,避免高頻 findViewById */
static class ViewHolder {
TextView tvName;
}
/**************** SectionIndexer ******************/
/** 索引段落的標題物件陣列 */
@Override
public Item[] getSections() {
return sections;
}
/** 索引 i 對應到列表中的哪個位置 */
@Override
public int getPositionForSection(int sectionIndex) {
if (sectionIndex >= sections.length) {
sectionIndex = sections.length - 1;
}
return sections[sectionIndex].listPosition;
}
/** 列表位置 position 屬於哪個索引段 */
@Override
public int getSectionForPosition(int position) {
if (position >= getCount()) {
position = getCount() - 1;
}
return getItem(position).sectionPosition;
}
}
整個實作的關鍵只有三步:把樹狀資料攤平成一維 List<Item>、用 type 標記哪些行會被釘住、實作 SectionIndexer 打通快速跳段。剩下的懸停動畫、陰影切換都由 PinnedSectionListView 內部處理。
有興趣的讀者可以進一步閱讀 PinnedSectionListView 的原始碼,看它是如何在 onScroll 中攔截第一個可見的 SECTION 並把它「釘」在頂部的——理解這個機制之後,要自己改寫一個也不難。
Android CardView 詳解與使用方法
CardView 是 Android 5.0 之後常被用來建立卡片式界面的元件。簡單來說,它像是在 FrameLayout 上加入圓角與陰影效果,因此很適合用於列表項、資
Android 位圖處理入門(一):徹底搞懂 BitmapFactory
只要碰過 Bitmap(位圖),就一定會和 BitmapFactory 打交道。今天我們就把這個類的廬山真面目看清楚。 先看官方定義: Creates Bitmap
Android Studio 實現 APK 版本更新:檢測、下載與自動安裝全流程
先放幾張效果圖,讓大家對要做成什麼樣有個概念:原理大家都懂,就不囉嗦了,直接看程式碼。裡面有幾段是我自己拿來測試的雜項,你可以直接刪掉。一、主介面 activity_ma
Android 事件處理機制:dispatchTouchEvent、onInterceptTouchEvent 與 onTouchEvent 全解析
在 Android 的所有事件類型中,Touch 事件是最複雜的一類。它包含 ACTION_DOWN、ACTION_MOVE、ACTION_UP、ACTION_CANCE