我有一个水平布局管理器和 RecylerView。从那以后,我通过设置非常高的 itemCount 并从中间开始制作了一个轮播。然后为了实现捕捉,我按照http://www.plattysoft.com/2015/06/16/snapping-items-on-a-horizo ntal-list/ 上的指南进行操作
Usually snapping works great but there are filters for the list (latest, most linked etc.) which when selected reload the list with new items.
如果列表朝正方向滚动(从右向左滑动),那么在重新加载后一切都很好。但是如果它在负方向滚动,那么在重新加载后它会捕捉到错误的位置(填充的长度)。
我尝试记录计算中使用的所有参数,但它们似乎是相同的,所以我不知道是什么原因造成的。
活动如下所示:
private RecyclerView myList;
private List<myItem> emptyList;
private myAdapter myAdapter;
final LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
Integer allPixels;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myAdapter = new myAdapter(this, emptyList);
myList.setAdapter(myAdapter);
myList.setLayoutManager(layoutManager);
myList.setHasFixedSize(true);
myList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
calculatePositionAndScroll(recyclerView);
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
allPixels += dx;
}
});
// get latest items
new getItems().execute();
}
// async task
public class getItems extends AsyncTask<ContentValues, Void, List<myItem>> {
protected void onPostExecute(List<myItem> result) {
myAdapter = new myAdapter(getApplicationContext(), result);
myList.swapAdapter(myAdapter, false);
allPixels = 0;
myList.scrollToPosition((100000 / 2));
calculatePositionAndScroll(myList);
}
}
private void calculatePositionAndScroll(RecyclerView recyclerView) {
int expectedPosition = Math.round((allPixels + padding - itemWidth) / itemWidth);
scrollListToPosition(recyclerView, expectedPosition);
}
private void scrollListToPosition(RecyclerView recyclerView, int expectedPosition) {
float targetScrollPos;
targetScrollPos = (expectedPosition * itemWidth) + itemWidth - padding;
float missingPx = targetScrollPos - allPixels;
Log.e("VARS", "expectedPosition: "+expectedPosition+" | itemWidth: "+itemWidth+" | padding: "+padding+
" | allPixels: "+allPixels+" | targetPos: "+targetScrollPos+" missingPx: "+missingPx);
if (missingPx > 5 || missingPx < -5) {
recyclerView.smoothScrollBy((int) missingPx, 0);
}
}
通常项目应如下所示:
但是在向左滚动并重新加载新列表后,如果像这样移动它: