添加片段插入列表视图项视图、片段、列表

由网友(死神不肯收留我)分享简介:我想为在ListView每个项目的片段,因为我想一些逻辑分离出来。我使用的为每个项目视图持有人。如果视图不存在,我创建了一个新的片段,并将其添加到容器中。 holder.mMyFragment =新MyFragment(mActivity,这一点);。mActivity.getSupportFragmentManag...

我想为在ListView每个项目的片段,因为我想一些逻辑分离出来。我使用的为每个项目视图持有人。如果视图不存在,我创建了一个新的片段,并将其添加到容器中。

  holder.mMyFragment =新MyFragment(mActivity,这一点);。mActivity.getSupportFragmentManager()调用BeginTransaction()加(R.id.my_container,holder.mMyFragment).commit()。 

另外每个项目,我叫holder.mMyFragment.setUi(数据源,位置)来设置基于数据源和位置在片段的UI。

我遇到的问题是我在初始化片段类onCreateView方法片段的UI元素,但是当我的片段添加到项目它不叫。所以后来当我打电话setUi(),它使用了一些UI元素的片段它抱怨一个NullPointerException异常。有没有人有一个建议?谢谢!

解决方案

 我想为在ListView每个项目的片段,因为我想一些逻辑分离出来。 

您不能使用片段作为列表项的看法,因为API不允许你 - 查看片段甚至不相关的,所以没有办法,你可以用它这样。制作自定义视图和使用适配器 getViewTypeCount getView 来使用不同的列表项的行为。

片段是由活动的FragmentManager或其他碎片的孩子FragmentManager管理;而列表项的意见是通过ListView控件和放大器管理; ListAdapter。您可以使用片段列表视图,而不是周围的其他方式。

在DW中怎么插入列表项目

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();

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

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.

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.

阅读全文

相关推荐

最新文章