【问题标题】:android - RecyclerView add new items move recycle to top of listandroid - RecyclerView 添加新项目将回收移动到列表顶部
【发布时间】:2021-09-06 08:44:21
【问题描述】:

我在 RecyclerView 滚动并到达 RecyclerView 末尾时添加了一些项目。这是我的代码:

rc_products.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (ViewType == ViewTypes.Grid) {
                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

                if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                    if (taskrunning != null && taskrunning == false && loadmore) {
                        page = page + 1;
                        getProducts(page);
                    }
                }
            }
        }
    });

当它到达RecyclerView 的末尾时,它会获取一些新数据并将新项目添加到我的适配器,这是之后运行的代码:

if (productAdaper == null) {
    productAdaper = new MyAdapter2(Productha.this, items_products);
    ScaleInAnimationAdapter scaldeAdapter = new ScaleInAnimationAdapter(productAdaper);
    scaldeAdapter.setDuration(300);
    rc_products.setAdapter(scaldeAdapter);
} else {
    productAdaper.addAll(items_products);
}

它工作正常,它也可以向我的RecyclerView 添加新项目,但是当它添加新项目时它会一直滚动到RecyclerView 的顶部。

如何防止它上升并使其在添加新数据时保持在原来的位置?

【问题讨论】:

  • 我们能看到productAdapter的代码吗?
  • 不清楚如何将新项目添加到RecyclerView。你在 `getProducts(page) 中这样做吗?
  • 是的,getProducts(page) 获取新数据

标签: java android android-recyclerview


【解决方案1】:

“每当您将新页面数据传递给回收站视图时。可能是适配器正在沿着旧数据重新加载整个数据。”

“你可以通过两种方式解决它:-

1 -> 如果您使用的是 arrayList() 适配器,请确保您使用“diffUtil”函数实现了适配器。

2 -> 我建议您尝试使用“Paging library”来实现适配器。它有助于加载和显示数据页面”

【讨论】:

  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
  • 试试 => medium.com/android-news/… 。如果仍然卡住,请告知。
猜你喜欢
  • 2017-01-11
  • 1970-01-01
  • 2016-12-15
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多