編輯:關於 Android 程式設計
GitHub 專案:https://github.com/JimiSmith/PinnedHeaderListView
要做「分組列表、滾動時當前組標題固定懸浮在頂部」的效果,GitHub 上有兩個不錯的選擇:PinnedSectionListView 與 PinnedHeaderListView。這篇選後者來讀,因為它的源碼更精簡,容易看清核心手法。
若你只想直接做出效果、對源碼沒興趣,可以跳去作者的另一篇自定義教學:PinnedHeaderListView 自定義實作。
整個專案只有四個值得看的類別:

類別宣告如下:
public abstract class SectionedBaseAdapter extends BaseAdapter
implements PinnedHeaderListView.PinnedSectionedHeaderAdapter {
它繼承 BaseAdapter,同時實作 PinnedHeaderListView 內部定義的介面。介面本身很精簡:
public interface PinnedSectionedHeaderAdapter {
boolean isSectionHeader(int position); // 該位置是否為組標題
int getSectionForPosition(int position); // 該位置屬於第幾組
View getSectionHeaderView(int section, View convertView, ViewGroup parent);
int getSectionHeaderViewType(int section);
int getCount();
}
抽象類別的實作如下:
/** 是否為組標題 */
@Override
public final boolean isSectionHeader(int position) {
int sectionStart = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
if (position == sectionStart) {
return true; // 正好是該組的起點
} else if (position < sectionStart) {
return false;
}
sectionStart += internalGetCountForSection(i) + 1; // +1 是標題本身
}
return false;
}
/** 依位置取得組號 */
@Override
public final int getSectionForPosition(int position) {
Integer cached = mSectionCache.get(position);
if (cached != null) {
return cached;
}
int sectionStart = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
int sectionEnd = sectionStart + internalGetCountForSection(i) + 1;
if (position >= sectionStart && position < sectionEnd) {
mSectionCache.put(position, i);
return i;
}
sectionStart = sectionEnd;
}
return 0;
}
/** 總筆數 = 各組元素數 + 各組標題數 */
@Override
public final int getCount() {
if (mCount >= 0) {
return mCount;
}
int count = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
count += internalGetCountForSection(i);
count++; // 組標題佔一格
}
mCount = count;
return count;
}
/** 該位置在本組內的索引 */
public int getPositionInSectionForPosition(int position) {
Integer cached = mSectionPositionCache.get(position);
if (cached != null) {
return cached;
}
int sectionStart = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
int sectionEnd = sectionStart + internalGetCountForSection(i) + 1;
if (position >= sectionStart && position < sectionEnd) {
int positionInSection = position - sectionStart - 1; // 減掉標題那一格
mSectionPositionCache.put(position, positionInSection);
return positionInSection;
}
sectionStart = sectionEnd;
}
return 0;
}
這幾個方法的規律很清楚:每一組在列表中的佔位是「1 個標題 + N 個元素」,所有的位置換算都是繞著這個不變式在算,並額外用兩個 Map 做快取避免重複遍歷。唯一留給子類別實作的是 getSectionHeaderView()。
BaseAdapter 的部分則靠 getView 分流:
@Override
public final View getView(int position, View convertView, ViewGroup parent) {
if (isSectionHeader(position)) {
return getSectionHeaderView(getSectionForPosition(position), convertView, parent);
}
return getItemView(getSectionForPosition(position),
getPositionInSectionForPosition(position), convertView, parent);
}
是標題就交給 getSectionHeaderView,否則交給 getItemView——兩個都是抽象方法,得在自己的 Adapter 裡實作。
public class PinnedHeaderListView extends ListView
implements OnScrollListener, AdapterView.OnItemClickListener {
它繼承 ListView,實作捲動與點擊監聽,並在每個建構子裡把自己掛上去:
public PinnedHeaderListView(Context context) {
super(context);
super.setOnScrollListener(this);
super.setOnItemClickListener(this);
}

紅框標出的都是關鍵方法,以下逐一拆解。
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
headerCount = getHeaderViewsCount();
// 沒有資料、關閉懸浮、或還停在 header 區間,就不處理
if (mAdapter == null || mAdapter.getCount() == 0 || !mShouldPin
|| (firstVisibleItem < headerCount)) {
mCurrentHeader = null;
mHeaderOffset = 0.0f;
for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) {
View header = getChildAt(i);
if (header != null) {
header.setVisibility(VISIBLE);
}
}
return;
}
firstVisibleItem -= getHeaderViewsCount(); // 扣掉 ListView 自身的 header
int section = mAdapter.getSectionForPosition(firstVisibleItem);
int viewType = mAdapter.getSectionHeaderViewType(section);
mCurrentHeader = getSectionHeaderView(section,
mCurrentHeaderViewType != viewType ? null : mCurrentHeader);
ensurePinnedHeaderLayout(mCurrentHeader); // 讓懸浮表頭完成量測與配置
mCurrentHeaderViewType = viewType;
mHeaderOffset = 0.0f;
for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) {
if (mAdapter.isSectionHeader(i)) {
View header = getChildAt(i - firstVisibleItem);
float headerTop = header.getTop();
float pinnedHeaderHeight = mCurrentHeader.getMeasuredHeight();
header.setVisibility(VISIBLE);
if (pinnedHeaderHeight >= headerTop && headerTop > 0) {
// 下一組的標題快頂上來了,此時懸浮表頭要往上讓位
mHeaderOffset = headerTop - header.getHeight();
} else if (headerTop <= 0) {
// 下一組標題已經到達頂端,原本的列表項先藏起來,改由懸浮表頭呈現
header.setVisibility(INVISIBLE);
}
}
}
invalidate();
}
幾個值得留意的細節:
mOnScrollListener.onScroll(...) 是為了保留外部自訂監聽的能力——因為建構子裡已經把自己設為監聽者,若不轉發,呼叫方設的監聽就會失效。ensurePinnedHeaderLayout() 負責對懸浮表頭做 measure 與 layout:private void ensurePinnedHeaderLayout(View header) {
if (header.isLayoutRequested()) {
int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), mWidthMode);
int heightSpec;
ViewGroup.LayoutParams lp = header.getLayoutParams();
if (lp != null && lp.height > 0) {
heightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
} else {
heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
header.measure(widthSpec, heightSpec);
header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());
}
}
layout 時 left=0、top=0,就是把它釘在左上角。
這個偏移量在 dispatchDraw 中生效:
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mAdapter == null || !mShouldPin || mCurrentHeader == null) {
return;
}
int saveCount = canvas.save();
// mHeaderOffset <= 0,等於把畫布往上推一段
canvas.translate(0, mHeaderOffset);
canvas.clipRect(0, 0, getWidth(), mCurrentHeader.getMeasuredHeight());
mCurrentHeader.draw(canvas);
canvas.restoreToCount(saveCount);
}
整個懸浮效果到這裡就完整了:onScroll 決定要懸浮哪一個表頭、要往上推多少;dispatchDraw 負責把這個表頭畫在最上層。
原專案的 onItemClick 有些問題,我在其基礎上做了修改。先定義自己的監聽介面:
public interface OnItemClickListener {
void onSectionItemClick(AdapterView<?> parent, View view, int section, int position, long id);
void onSectionClick(AdapterView<?> parent, View view, int section, long id);
void onHeaderClick(AdapterView<?> parent, View view, int position, long id);
void onFooterClick(AdapterView<?> parent, View view, int position, long id);
}
四個回呼分別對應:組內元素被點擊、組標題被點擊、ListView 的 header 被點擊、ListView 的 footer 被點擊。
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView 自身的 header
if (position < headerCount) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onHeaderClick(parent, view, position, id);
}
return;
}
// ListView 自身的 footer
if (mAdapter != null && position >= headerCount + mAdapter.getCount()) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onFooterClick(parent, view,
position - headerCount - mAdapter.getCount(), id);
}
return;
}
// 其餘屬於分組內容
position -= headerCount;
// 有 header 時,Adapter 會被 HeaderViewListAdapter 包一層,要先剝開
SectionedBaseAdapter adapter;
if (parent.getAdapter() instanceof HeaderViewListAdapter) {
HeaderViewListAdapter wrapper = (HeaderViewListAdapter) parent.getAdapter();
adapter = (SectionedBaseAdapter) wrapper.getWrappedAdapter();
} else {
adapter = (SectionedBaseAdapter) parent.getAdapter();
}
int section = adapter.getSectionForPosition(position);
int positionInSection = adapter.getPositionInSectionForPosition(position);
if (positionInSection == -1) {
// 點到組標題
if (mOnItemClickListener != null) {
mOnItemClickListener.onSectionClick(parent, view, section, id);
}
} else {
// 點到組內元素
if (mOnItemClickListener != null) {
mOnItemClickListener.onSectionItemClick(parent, view, section, positionInSection, id);
}
}
}
這段的重點是兩件事:位置要記得扣掉 ListView 自身的 header 數量;以及當 Adapter 被 HeaderViewListAdapter 包裝時,必須先取出被包裝的 SectionedBaseAdapter,否則位置換算會全部錯位。
這個實作之所以值得讀,是因為它沒有任何魔法:一個抽象 Adapter 負責把「分組 + 標題」攤平成一維列表並提供位置換算;一個自定義 ListView 在 onScroll 裡算出該懸浮哪一格、要往上讓多少,再在 dispatchDraw 中把表頭畫到最上層。理解了這兩件事,之後要加上陰影、漸層、吸附動畫都只是延伸變化。
Android 網絡狀態判斷知識小結
Android 中如何判斷當前網絡是否可用應用場景:在程式執行時判斷當前是否有可用的網絡連接。當前有可用網絡時,如下圖:當前沒有可用網絡時,如下圖:實現步驟如下:1、獲取
Android JNI 與 NDK 開發入門:從 Builder 設定到第一個 so
NDK 讓 Android 開發者能用 C 或 C++ 撰寫原生程式,並打包成 so 動態庫。自 NDK r7 之後,Windows 環境已可直接使用 ndk-build
深入原理:Android 創建桌面快捷方式 Shortcut
網路上寫過創建桌面快捷方式的文章很多,但大部分只講了「怎麼用」,其實技術操作起來都很簡單,問題是下次你還記得嗎?根本原因還是不清楚原理。今天我就來講講 shortcut
Activity 啟動模式之 standard:每次啟動都是新實例
standard 是系統默認的啟動模式,規則很簡單:每次激活 Activity 都會創建新實例,並放入 Activity 棧中。 布局 放一個按鈕,點擊後用顯式 Int