一、scrollToPosition概述
在Android開發中,常常需要對ListView或者RecyclerView進行滾動控制。scrollToPosition就是一個控制滾動位置的控制項。它可以讓我們輕鬆的讓ListView或者RecyclerView在指定的Item處停止滾動,從而實現定位到指定位置的操作。
二、scrollToPosition的使用方法
以使用RecyclerView為例,RecyclerView的scrollToPosition方法可以實現指定Item位置的滾動。下面是使用示例:
//獲取RecyclerView實例 RecyclerView recyclerView = findViewById(R.id.recycler_view); //設置LayoutManager recyclerView.setLayoutManager(new LinearLayoutManager(this)); //設置adapter MyAdapter adapter = new MyAdapter(data); recyclerView.setAdapter(adapter); //滾動到指定位置 recyclerView.scrollToPosition(position);
上述代碼實現了RecyclerView在指定位置position停止滾動的效果。其中,position是指要滾動到的數據項的位置,從0開始計算。
三、scrollToPosition的原理
在RecyclerView的源碼中,scrollToPosition的核心實現方法就是scrollToPositionInt。
void scrollToPositionInt(int position, int subposition, boolean immediate) {
LayoutManager lm = mLayout;
if (lm == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
lm.scrollToPosition(position);
if (immediate || !mIsAttached) {
// immediate cancel any current scroll animation
stopScroll();
}
if (mPostUpdatesOnAnimation && mEatRequestLayout == 0) {
if (lm != null && lm.isSmoothScrolling()) {
// if we are smooth scrolling, see if the list needs to redraw and intercept
if (subposition == RecyclerView.NO_POSITION) {
if (lm.getChildCount() == 0) {
dispatchLayout();
}
} else if (lm.findViewByPosition(subposition) == null) {
// we are scrolling to child that is not ready, we need to offset to something else
// run a layout, offset, then scroll again
Log.e(TAG, "scrollToPosition doesn't support stack from end. Ignoring");
} else {
lm.scrollToPosition(subposition);
}
mState.mTargetPosition = position;
mState.mTargetOffset = mOrientationHelper.getDecoratedStart(lm.getChildAt(0))
- mOrientationHelper.getStartAfterPadding();
mState.mTargetOffset -= mLayoutState.mScrollOffset;
return;
} else {
// no smooth scrolling -> no need for an extra layout step
dispatchLayout();
}
}
}
可以看出,scrollToPositionInt的基本實現原理就是調用LayoutManager的scrollToPosition方法進行滾動,然後判斷是否需要對List重新布局(通過dispatchLayout()方法實現)。
四、scrollToPosition的注意事項
1、scrollToPosition實現滾動的精度不高,如果要實現更高精度的滑動操作,建議使用smoothScrollToPosition。
2、當RecyclerView或者ListView頂部留有固定的Header,需要滑動到Header下面的內容時,可能需要自己手動計算滾動距離,並使用scrollBy方法進行滾動。
3、scrollToPosition只適用於已經布局完成的可見控制項,如果想要滾動到非可見的區域或者滾動到未完成布局的位置,建議配合Post方法使用。
五、結語
scrollToPosition是一個非常實用的控制項,可以對RecyclerView和ListView進行滾動位置的控制。但是,需要注意使用的精度問題,並且在需要滾動到非可見區域或者未完成布局的位置時,需要特別注意。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/243080.html
微信掃一掃
支付寶掃一掃