对于屏幕外项目,RecyclerView findViewHolder为null

时间:2015-09-21 16:48:57

标签: android android-recyclerview recycler-adapter

[第一次提问者和第一次安装android编码器,所以如果我做错了就道歉]

我试图在我的回收商上更改项目视图中的值。但是,如果该项目视图恰好在屏幕外,则findViewBy [layout,adapter或id]将显示为null。

public void setUserActive(UserListAdapter adapter, RecyclerView recyclerView, int position, View v) {recyclerView.findViewHolderForItemId(adapter.getItemId(position));
    TextView txtActive = (TextView) vh.itemView.findViewById(R.id.user_isActive);
    txtActive.setText("Active");
    UserListAdapter.ViewHolder inactivevh = (UserListAdapter.ViewHolder) recyclerView.findViewHolderForItemId(adapter.getItemId(adapter.getActiveUserPosition()));
    TextView txtInActive = (TextView) inactivevh.itemView.findViewById(R.id.user_isActive);
    txtInActive.setText("");
    adapter.setActiveUserPosition(position);
}

我尝试了几种不同的方式,使用

  UserListAdapter.ViewHolder vh = (UserListAdapter.ViewHolder) recyclerView.findViewHolderForLayoutPosition(position);

UserListAdapter.ViewHolder inactivevh = (UserListAdapter.ViewHolder) recyclerView.findViewHolderForAdapterPosition(position)

当应该处于inactivevh的视图不在屏幕上时,它们都会失败。

我已将适配器设置为hasStableIDs = true notifydatasetchanged似乎也无济于事。

1 个答案:

答案 0 :(得分:8)

如果某个项目在屏幕上(布局),您可以使用您描述的方法方便地获取其视图保持器。 如果某个项目不在屏幕上,它会在通过onBindViewHolder滚动后立即更新。如果它没有滚动进入,则不会向用户显示任何尝试更新它是浪费处理能力(除了不可能,因为该项目没有分配视图持有者)。

含义:以onBindViewHolder能够提取最新数据的方式实现适配器。看起来你已经完成所有设置并且可以使用它:

public void setUserActive(UserListAdapter adapter, RecyclerView recyclerView, int position) {
    // Retrieve the old active user ID so we can mark him deactivated.
    final int oldUserActivePosition = adapter.getActiveUserPosition();

    // Setup the adapter with current data.
    adapter.setActiveUserPosition(position);

    // Do NOT use stable IDs and this method. It just doesn't work as expected.
    // recyclerView.findViewHolderForItemId(adapter.getItemId(position));

    // Activate new user.
    UserListAdapter.ViewHolder holder = (UserListAdapter.ViewHolder) recyclerView.findViewHolderForAdapterPosition(position);
    if (holder == null) {
        // The item is off screen, no need to update it yet.
    } else {
        // Update the on screen item. The logic is already implemented in the adapter.
        adapter.onBindViewHolder(holder, position);
    }

    // Deactivate previous user.
    holder = (UserListAdapter.ViewHolder) recyclerView.findViewHolderForAdapterPosition(oldUserActivePosition);
    if (holder != null) {
        adapter.onBindViewHolder(holder, oldUserActivePosition);
    }
}

当然,简化代码中的if-else块。

编辑:

我刚刚意识到原始解决方案是多么复杂。只要适配器可以对onBindViewHolder中所需的所有事件作出反应,并且绑定非常简单,这就足够了:

public void setActiveUserPosition(int position) {
    if (mActiveUserPosition != position) {
        int oldPosition = mActiveUserPosition;
        mActiveUserPosition = position;
        notifyItemChanged(oldPosition);
        notifyItemChanged(position);
    }
}

现在需要调用的只是adapter.setActiveUserPosition(position);,这会使setUserActive方法过时。