StaggeredGridLayoutManager 瀑布流返回顶部时出现跳跃

来源:互联网 发布:除法公式有几种算法 编辑:程序博客网 时间:2024/06/11 12:58

    使用RecyclerView搭配StaggeredGridLayoutManager实现瀑布流时,一般会在Adapter的onBindViewHolder()方法里加载图片,图片高度自适应,使得item的排布错落有致。但是当我们下拉到底部之后,上拉的时候,每一个item又会执行一遍onBindViewHolder()方法,会导致我们滑回到顶部的时候,瀑布流的几个流可能不是平齐的,StaggeredGridLayoutManager会调整排布顺序,使得几个流的顶部平齐,产生了跳跃的现象。

       解决办法,给StaggeredGridLayoutManager 的setGapStrategy方法设成GAP_HANDLING_NONE,这样setAutoMeasureEnabled方法就会被置位false。

    /**     * Sets the gap handling strategy for StaggeredGridLayoutManager. If the gapStrategy parameter     * is different than the current strategy, calling this method will trigger a layout request.     *     * @param gapStrategy The new gap handling strategy. Should be     *                    {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} or {@link     *                    #GAP_HANDLING_NONE}.     * @see #getGapStrategy()     */    public void setGapStrategy(int gapStrategy) {        assertNotInLayoutOrScroll(null);        if (gapStrategy == mGapStrategy) {            return;        }        if (gapStrategy != GAP_HANDLING_NONE &&                gapStrategy != GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS) {            throw new IllegalArgumentException("invalid gap strategy. Must be GAP_HANDLING_NONE "                    + "or GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS");        }        mGapStrategy = gapStrategy;        setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE);        requestLayout();    }

        所以我们只需要写一下代码即可:

        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        lv_collect.setOnScrollListener(new RecyclerView.OnScrollListener() {            @Override            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {                super.onScrollStateChanged(recyclerView, newState);                StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager)recyclerView.getLayoutManager();                layoutManager.invalidateSpanAssignments();            }            @Override            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {                super.onScrolled(recyclerView, dx, dy);            }        });


阅读全文
0 0
原创粉丝点击