編輯:關於 Android 程式設計
我們都知道 RecyclerView 可以透過把 LayoutManager 設為 StaggeredGridLayoutManager 來實現瀑布流,預設還有 LinearLayoutManager(線性布局)與 GridLayoutManager(網格布局)。但 RecyclerView 能做的遠不止於此——透過重寫 LayoutManager,我們能按自己的意志實現更複雜的效果,而且把控制項與顯示效果解耦後,就能動態改變顯示樣式。
想像有這麼一個界面:先以列表展示一組資料,點擊按鈕後改用網格展示另一組。傳統做法可能是在同一布局放一個 ListView 和一個 GridView,靠可見性切換;而用 RecyclerView,只需 setAdapter 換資料、setLayoutManager 換樣式即可,既簡化了布局,邏輯也更乾淨。
下面我們就來實作一個弧形的 RecyclerView,以及一個會隨滾動在指定位置放大的 RecyclerView,並加上類似 ViewPager 的回彈效果。
通常重寫一個 LayoutManager 可分為:指定預設的 LayoutParams、測量並記錄每個 item 的資訊、回收與放置各個 item、處理滾動。
繼承 LayoutManager 後,有個必須重寫的方法 generateDefaultLayoutParams(),它指定每個子 view 預設的 LayoutParams,並在 getViewForPosition() 回傳子 view 前套用上去:
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
接著重寫 onLayoutChildren(),這是 LayoutManager 的主要入口,會在初始化布局及 adapter 資料變動時呼叫,我們在此測量並初始化 item。
先補充一下 RecyclerView 的兩種緩存機制:scrap heap 與 recycle pool。scrap heap 較輕量,會直接快取當前 view 而不經過 adapter;當一個 view 被 detach 後就會暫存進去。而 recycle pool 裡的 view 被視為帶有「錯誤資料」(之後需拿出重用顯示別的位置),所以會傳給 adapter 重新綁定。當需要顯示新 view 時,recycler 會先檢查 scrap heap 中 position 相符的 view,有就直接回傳;沒有就從 recycle pool 取一個交給 adapter 呼叫 bindViewHolder() 綁定資料後回傳。
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getItemCount() == 0) {
detachAndScrapAttachedViews(recycler);
offsetRotate = 0;
return;
}
// 計算子 view 大小
if (getChildCount() == 0) {
View scrap = recycler.getViewForPosition(0);
addView(scrap);
measureChildWithMargins(scrap, 0, 0);
mDecoratedChildWidth = getDecoratedMeasuredWidth(scrap);
mDecoratedChildHeight = getDecoratedMeasuredHeight(scrap);
startLeft = contentOffsetX == -1 ? (getHorizontalSpace() - mDecoratedChildWidth) / 2 : contentOffsetX;
startTop = contentOffsetY == -1 ? 0 : contentOffsetY;
mRadius = mDecoratedChildHeight;
detachAndScrapView(scrap, recycler);
}
// 記錄每個 item 的初始狀態
float rotate = firstChildRotate;
for (int i = 0; i < getItemCount(); i++) {
itemsRotate.put(i, rotate);
itemAttached.put(i, false);
rotate += intervalAngle;
}
detachAndScrapAttachedViews(recycler);
fixRotateOffset();
layoutItems(recycler, state);
}
getItemCount() 取得的是資料總數,getChildCount() 則是目前已加入的子 View 數量。因為本專案所有 view 大小一致,只測量 position 為 0 的 view 即可。itemsRotate 記錄每個 item 的旋轉角度,offsetRotate 是旋轉偏移量(每個 item 的角度加上它就是最終顯示角度),itemAttached 則標記該 item 是否已加入當前界面。
private void layoutItems(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (state.isPreLayout()) return;
// 移除超出範圍的 view
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
int position = getPosition(view);
if (itemsRotate.get(position) - offsetRotate > maxRemoveDegree
|| itemsRotate.get(position) - offsetRotate < minRemoveDegree) {
itemAttached.put(position, false);
removeAndRecycleView(view, recycler);
}
}
// 加入尚未 attach 且在範圍內的 view
for (int i = 0; i < getItemCount(); i++) {
if (itemsRotate.get(i) - offsetRotate <= maxRemoveDegree
&& itemsRotate.get(i) - offsetRotate >= minRemoveDegree) {
if (!itemAttached.get(i)) {
View scrap = recycler.getViewForPosition(i);
measureChildWithMargins(scrap, 0, 0);
addView(scrap);
float rotate = itemsRotate.get(i) - offsetRotate;
int left = calLeftPosition(rotate);
int top = calTopPosition(rotate);
scrap.setRotation(rotate);
layoutDecorated(scrap,
startLeft + left, startTop + top,
startLeft + left + mDecoratedChildWidth,
startTop + top + mDecoratedChildHeight);
itemAttached.put(i, true);
}
}
}
}
prelayout 是 RecyclerView 繪製動畫的階段,本專案不需處理動畫故直接 return。這裡先把超出範圍的子 view remove 並加入 recycle pool(呼叫 removeAndRecycleView 即可),再把尚未 attach 的 item 測量後,依當前角度用國中數學算出 x、y 座標加入布局。核心的座標計算如下:
private int calLeftPosition(float rotate) {
return (int) (mRadius * Math.cos(Math.toRadians(90 - rotate)));
}
private int calTopPosition(float rotate) {
return (int) (mRadius - mRadius * Math.sin(Math.toRadians(90 - rotate)));
}
現在 LayoutManager 已能顯示弧形列表,只差讓它滾起來:
@Override
public boolean canScrollHorizontally() {
return true;
}
顧名思義,這個方法設定能否橫向滾動,對應的還有 canScrollVertically()。
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
int willScroll = dx;
float theta = dx / DISTANCE_RATIO; // 每個 dx 對應的旋轉角度
float targetRotate = offsetRotate + theta;
// 處理邊界
if (targetRotate < 0) {
willScroll = (int) (-offsetRotate * DISTANCE_RATIO);
} else if (targetRotate > getMaxOffsetDegree()) {
willScroll = (int) ((getMaxOffsetDegree() - offsetRotate) * DISTANCE_RATIO);
}
theta = willScroll / DISTANCE_RATIO;
offsetRotate += theta;
// 重新計算每個 item 的角度與 x、y
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
float newRotate = view.getRotation() - theta;
int offsetX = calLeftPosition(newRotate);
int offsetY = calTopPosition(newRotate);
...
}
// 處理各 item 的回收
layoutItems(recycler, state);
return willScroll;
}
若是縱向滾動則改寫 scrollVerticallyBy。這裡把滑動距離按一定比例轉成旋轉角度,依新角度重繪子 view,最後呼叫 layoutItems 處理回收。至此,一個弧形(圓形)的 LayoutManager 就完成了。
滑動放大的 LayoutManager 實作類似——在中心點 scale 最大,距離中心 x 座標取絕對值後轉為對應 scale 即可:
private float calculateScale(int x) {
int deltaX = Math.abs(x - (getHorizontalSpace() - mDecoratedChildWidth) / 2);
float diff = 0f;
if ((mDecoratedChildWidth - deltaX) > 0)
diff = mDecoratedChildWidth - deltaX;
return (maxScale - 1f) / mDecoratedChildWidth * diff + 1;
}
想實現類似 ViewPager 鎖定到某一頁的效果怎麼做?一開始想對 scrollHorizontallyBy() 的 dx 動手腳,但效果不理想;又想到重寫 smoothScrollToPosition 並在 IDLE 狀態呼叫,卻總有偏移。最後查 API 發現 RecyclerView 有個 smoothScrollBy 方法,會依給定的偏移量呼叫 scroll 方法。於是我們只要寫個 OnScrollListener 掛上去即可:
public class CenterScrollListener extends RecyclerView.OnScrollListener {
private boolean mAutoSet = true;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (!(layoutManager instanceof CircleLayoutManager)
&& !(layoutManager instanceof ScrollZoomLayoutManager)) {
mAutoSet = true;
return;
}
if (!mAutoSet) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (layoutManager instanceof ScrollZoomLayoutManager) {
final int scrollNeeded = ((ScrollZoomLayoutManager) layoutManager).getOffsetCenterView();
recyclerView.smoothScrollBy(scrollNeeded, 0);
} else {
final int scrollNeeded = ((CircleLayoutManager) layoutManager).getOffsetCenterView();
recyclerView.smoothScrollBy(scrollNeeded, 0);
}
}
mAutoSet = true;
}
if (newState == RecyclerView.SCROLL_STATE_DRAGGING
|| newState == RecyclerView.SCROLL_STATE_SETTLING) {
mAutoSet = false;
}
}
}
recyclerView.addOnScrollListener(new CenterScrollListener());
還要在自定義 LayoutManager 中補上取得滾動偏移量的方法:
public int getCurrentPosition() {
return Math.round(offsetRotate / intervalAngle);
}
public int getOffsetCenterView() {
return (int) ((getCurrentPosition() * intervalAngle - offsetRotate) * DISTANCE_RATIO);
}
透過重寫 LayoutManager,我們把「資料」與「顯示效果」徹底解耦,得以輕鬆打造弧形、滑動放大等富創意的列表樣式。完整程式碼已上傳 GitHub,有興趣可前往參考。
自定義滑動按鈕 MyToggleButton
自定義滑動按鈕的實作 滑動按鈕本質上是一個自定義 View,需要處理背景圖、滑塊圖、觸摸事件與狀態回呼。透過滑塊的位置,可以判斷目前是開啟或關閉。 初始化與測量 建立
Android 中的消息傳遞:詳解廣播機制
廣播機制簡介 Android 中的廣播機制非常靈活,每個應用程序都可以對自己感興趣的廣播進行註冊,並且只會收到自己關心的內容。這些廣播可能來自系統,也可能來自其他應用程序
ViewPager 實現啟動引導頁:圖片、圓點與進入按鈕的完整閉環
安裝一個新 App,第一次打開時基本都會有引導頁——可能是功能介紹,可能是活動宣傳,也可能是使用說明。它們通常支持左右滑動,底部有幾個小圓點指示「共幾頁、當前第幾頁」,滑
Android 記憶體洩漏排查實戰(上):從 Heap 到 MAT 的診斷流程
一、先把問題定義清楚 做 Android 開發,「記憶體洩漏」大概是最高頻出現的效能問題之一。它的定義其實很單純:一個物件已經不再被使用,卻因為有其他物件仍持有它的參考,