将片段添加到列表视图项中 [英] Add fragment into listview item

查看:36
本文介绍了将片段添加到列表视图项中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为列表视图中的每个项目都有一个片段,因为我想分离一些逻辑.我为每个项目使用一个视图持有者.如果视图不存在,我会创建一个新片段并将其添加到容器中.

I want to have a fragment for each item in a listview, because I want to separate some logic out. I am using a view holder for each item. If the view doesn't exist, I create a new fragment and add it into the container.

holder.mMyFragment = new MyFragment(mActivity, this);
mActivity.getSupportFragmentManager().beginTransaction().add(R.id.my_container, holder.mMyFragment).commit();

同样对于每个项目,我调用 holder.mMyFragment.setUi(dataSource, position) 来根据数据源和位置设置片段的 UI.

Also for each item, I call holder.mMyFragment.setUi(dataSource, position) to set UI of the fragment based on the data source and position.

我遇到的问题是我在片段类的 onCreateView 方法中初始化片段的 UI 元素,但是当我将片段添加到项目时没有调用它.所以稍后当我调用 setUi() 时,它在片段中使用了一些 UI 元素,它会抱怨 NullPointerException.有人有建议吗?谢谢!

The problem I'm having is I initialize the UI elements of fragment in onCreateView method of the fragment class, but it's not called when I add the fragment to the item. So later when I call setUi() which uses some UI elements in fragment it complains a NullPointerException. Does anyone have a suggestion? Thanks!

推荐答案

我想为列表视图中的每个项目都有一个片段,因为我想分离一些逻辑.

I want to have a fragment for each item in a listview, because I want to separate some logic out.

您不能将片段用作列表项视图,因为 API 不允许您 - ViewFragment 甚至不相关,因此您无法像那样使用它.制作自定义视图并使用适配器 getViewTypeCountgetView 来使用不同的列表项行为.

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 由 Activity 的 FragmentManager 或其他 Fragments 子 FragmentManager 管理;而列表项视图由 ListView & 管理列表适配器.您可以在 Fragment 中使用 ListViews,但不能反过来.

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.

这篇关于将片段添加到列表视图项中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆