在我的RecyclerView中,我需要将我的项目的一部分替换为片段。但只替换回收站视图中的第一个项目。我做错了什么?
我的容器(在回收器视图项中):

...
<FrameLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/container" />
...

我在RecyclerView适配器中的更新代码:
...
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

...

MyFragment fragment = MyFragment.newInstance("fragment1");
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();

...

}
...

最佳答案

我终于找到了解决办法。问题是我设置了一个普通的容器id。但是在recycler视图中需要为每个项目设置唯一的容器id。
所以,现在我的代码是:

MyFragment fragment = MyFragment.newInstance("fragment1");
fragmentManager.beginTransaction().replace(unique_id_here, fragment).commit();

如果有人会有用,这里是我的完整代码(Recycler视图中的实现框架):
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{

...

// Delete old fragment
int containerId = holder.mediaContainer.getId();// Get container id
Fragment oldFragment = fragmentManager.findFragmentById(containerId);
if(oldFragment != null) {
    fragmentManager.beginTransaction().remove(oldFragment).commit();
}

int newContainerId = GetUniqueID();// My method
holder.mediaContainer.setId(newContainerId);// Set container id

// Add new fragment
MyFragment fragment = MyFragment.newInstance("fragment1");
fragmentManager.beginTransaction().replace(newContainerId, fragment).commit();

...

}

07-28 01:52
查看更多