简体   繁体   English

如何在 notifyDataSetChanged 上禁用 recyclerview 滚动到顶部(第一项)

[英]How to disable recyclerview scroll to top (1st item) on notifyDataSetChanged

I have fixed number of items in recycler view, but I update data every 10 seconds and calling notifyDataSetChanged();我在回收站视图中有固定数量的项目,但我每 10 秒更新一次数据并调用 notifyDataSetChanged();

When I scrolled to Nth item (EX:20th item) and on notifyDataSetChanged() called recycler view getting refreshed and auto-scroll back to 1st item.当我滚动到第 N 项(EX:第 20 项)并在调用回收器视图的 notifyDataSetChanged() 上刷新并自动滚动回第一项时。 How can I stop scrolling and update the recycler view?如何停止滚动并更新回收站视图? Thanks in advance.提前致谢。

You can create a view type and holder for your first item then set setIsRecyclable您可以为您的第一个项目创建一个view type和持有人,然后设置setIsRecyclable

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    if (holder instanceof HeaderViewHolder ) {
        ((HeaderViewHolder ) holder).setIsRecyclable(false);
        ((HeaderViewHolder ) holder).bind(mData.get(position));
    }
}

Using onSaveInstanceState you will save the state or current position of your recyclerview .Just like this.使用onSaveInstanceState您将保存您的recyclerview的状态或当前位置。就像这样。

Create veriable in your activity在您的活动中创建真实的

Parcelable recylerViewList; //this will store the position

then create this method to fetch recyclerview state然后创建此方法以获取recyclerview状态

void storeInstance() {
    AttachmentsActivity.recylerViewList=mRecyclerView?.layoutManager?.onSaveInstanceState()
}// call this method before notifyDataSetChanged()

Create method to restore the state恢复状态的创建方法

    void restore() //call this method after notifyDataSetChanged()
    {
     mRecyclerView?.layoutManager?.onRestoreInstanceState(recylerViewList)
    }

Make sure you have to call this methods in activity or through activity object .确保您必须在activity或通过activity object调用此methods

You should find which items changed and use adapter.notifyItemChanged(itemChangedPosition) instead of notifyDatasetChanged()您应该找到更改的项目并使用adapter.notifyItemChanged(itemChangedPosition)而不是notifyDatasetChanged()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM