Mikhail Mikhail -4 years ago 191
Android Question

Fragment replacing in RecyclerView item

In my RecyclerView I need replace part of my item to my fragment. But replacing only first item in recycler view. What I am doing is wrong?

My container (in recycler view item):

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


My update code in RecyclerView adapter:

...
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

...

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

...

}
...

Answer Source

I finnaly found solution. The problem is I set a normal container id. But in recycler view need set unique container id for each item.

So, my code now this:

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

If someone will be useful, here is my complete code (implementation frament in recycler view):

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(newId);// Set container id

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

...

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download