RecyclerView 在我滚动之前不会更新子项

问题描述 投票:0回答:2

我想我已经阅读了所有类似问题的所有答案,并且没有一个似乎对我有用。这让我抓狂,我在这上面花了太多时间。

我正在实现一个

RecyclerView
这里,但我一生都无法更新它的孩子们。发生的情况是,在我更新后,屏幕上没有任何变化,除非我开始滚动。一旦我滚动它就会更新完美

这是我的代码:

public void updateDataAtIndex(final int indexToUpdate, ReadableMap updatedChild) {
    if (updatedChild != null) {
        if (this.data != null && this.data.size() > indexToUpdate) {
            this.data.set(indexToUpdate, updatedChild);
            final SPAdapter self = this;
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    System.out.println("\n@@@@@@@@@@@@@@@@@ Updating: "+indexToUpdate);
                    self.notifyItemChanged(indexToUpdate);
                }
            });
        }
    }
}

这是完整的适配器: https://github.com/SudoPlz/react-native-synchronous-list/blob/master/lib/android/src/main/java/com/sudoplz/rnsynchronouslistmanager/Views/List/SPAdapter.java#L109

android android-recyclerview react-native recyclerview-layout
2个回答
12
投票

这是一个反应原生问题

¯\_(ツ)_/¯

我通过拦截

requestLayout
解决了这个问题,如下所示:

protected boolean mRequestedLayout = false;

@Override
    public void requestLayout() {
        super.requestLayout();
        // We need to intercept this method because if we don't our children will never update
        // Check https://stackoverflow.com/questions/49371866/recyclerview-wont-update-child-until-i-scroll
        if (!mRequestedLayout) {
            mRequestedLayout = true;
            this.post(new Runnable() {
                @SuppressLint("WrongCall")
                @Override
                public void run() {
                    mRequestedLayout = false;
                    layout(getLeft(), getTop(), getRight(), getBottom());
                    onLayout(false, getLeft(), getTop(), getRight(), getBottom());
                }
            });
        }
    }

终于成功了.. 感谢发现解决方法的这位无名英雄。


0
投票

这是一个解决方案。

这会强制布局完全刷新项目。根据您的情况进行调整。

fun RecyclerView.forceLayout() {

  // Tell adapter the data has changed
  adapter?.notifyDataSetChanged()

  // Force the layout to move
  // This will render all items in view again
  scrollBy(0, 0)

}

你会认为 React Native 会正确处理 native UI..

© www.soinside.com 2019 - 2024. All rights reserved.