Android RecyclerView捕捉到错误的位置

时间:2015-08-06 10:18:34

标签: android carousel android-recyclerview snapping

我有一个水平布局管理器和RecylerView。从那时起,我通过设置非常高的itemCount并从中间开始制作旋转木马。 然后为了实现捕捉,我按照http://www.plattysoft.com/2015/06/16/snapping-items-on-a-horizontal-list/

的指南进行了操作

通常捕捉效果很好但是列表中有过滤器(最新,链接最多等),选中后会用新项重新加载列表。

如果列表向正方向滚动(从右向左滑动),则在重新加载后一切都很棒。但如果它是向负方向滚动,那么在重新加载后它会捕捉到错误的位置(填充的长度)。

我尝试记录计算中使用的所有参数,但它们似乎是相同的,所以我对导致这种情况的原因感到迷茫。

活动如下:

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);
    }

}

通常情况下,项目应如下所示:

但是在向左滚动并使用新列表重新加载后如果像这样移动:

0 个答案:

没有答案