Add fragment into listview item
Solution 1:
"THERE IS A SOLUTION" for this.
The issue is, you cannot add fragment directly to the container(FrameLayout) with same "id" in listview as you have done in the above code.
The trick is, create listview(Recyclerview) of "LinearLayout". Then dynamically create FrameLayout in adapter and assign different id's for each. Inflate Fragment to FrameLayout and this FrameLayout to LinearLayout.
@Override
protected void onBindBasicItemView(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof VideoHomeViewHolder) {
VideoHomeViewHolder videoHomeViewHolder = (VideoHomeViewHolder) holder;
FrameLayout frameLayout = new FrameLayout(mContext);
frameLayout.setId(position+1); //since id cannot be zero
FragmentHelper.popBackStackAndReplace(mFragmentManager, frameLayout.getId(),
new ShowLatestVideosFragment(mShowLatestVideosItems.get(position)));
videoHomeViewHolder.linearLayout.addView(frameLayout);
}
}
Solution 2:
I want to have a fragment for each item in a listview, because I want to separate some logic out.
You can't use fragment as list item views because the API doesn't allow you - View
and Fragment
aren't even related so there's no way you can use it like that. Make custom views and use adapter getViewTypeCount
and getView
to use different list item behavior.
Fragment are managed by Activity's FragmentManager or by other Fragments child FragmentManager; while list item views are managed by ListView & ListAdapter. You can use ListViews in Fragments, but not the other way around.