Andrain
Andrain

Reputation: 910

adding a fragments multiple times in linear layout programmatically

I want to add a fragment multiple time in the linear layout. For this purpose I'm using a For loop and passing data to the fragment. Each index has different data. My current problem is this I can only see the last fragment on the screen multipe times probably it is hiding the top fragment or any other reason. Don't understand what's the issue.

      categoryArrayList = dbHelper.getChannelInfo();
      fragmentManager =getSupportFragmentManager();
      ft = fragmentManager.beginTransaction();
      for (int i = 0; i<categoryArrayList.size(); i++) {

        SubFragment frag = new SubFragment();
          Bundle bundle = new Bundle();
        bundle.putInt("ID", (categoryArrayList.get(i).getChannelCategoryId()));
        bundle.putString("categoryName", categoryArrayList.get(i).getChannelName());
            frag.setArguments(bundle);
            ft.add(R.id.container, frag,"fragment"+i);
    }
    ft.commit();
}
}

xml:

<LinearLayout
  android:id="@+id/container"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  android:layout_marginTop="50dp"
  android:background="#252424"
  android:layout_below="@id/headercontainer"
  android:layout_marginLeft="30dp">

Upvotes: 0

Views: 258

Answers (1)

Mike M.
Mike M.

Reputation: 39191

You're using the same Bundle for each Fragment's arguments, and FragmentTransactions happen asynchronously, so when they finally execute, the Fragments are all reading the same arguments.

You presumably have something like the following before the loop:

Bundle bundle = new Bundle();

Move that to inside the for loop, before the put*() calls.

Upvotes: 1

Related Questions