我想为列表视图中的每个项目都有一个片段,因为我想分离出一些逻辑。我为每个项目使用一个视图持有者。如果视图不存在,我将创建一个新片段并将其添加到容器中。
holder.mMyFragment = new MyFragment(mActivity, this);
mActivity.getSupportFragmentManager().beginTransaction().add(R.id.my_container, holder.mMyFragment).commit();
另外,对于每个项目,我调用holder.mMyFragment.setUi(dataSource,position)来根据数据源和位置设置片段的UI。
我遇到的问题是我在片段类的 onCreateView 方法中初始化片段的 UI 元素,但当我将片段添加到项目时它不会被调用。因此,稍后当我调用 setUi()(它在片段中使用一些 UI 元素)时,它会抱怨 NullPointerException。有人有建议吗?谢谢!
"有一个解决方案“ 为了这。
问题是,你无法将fragment直接添加到容器中(FrameLayout) 在列表视图中具有与上面代码中相同的“id”。
The trick就是,创建“LinearLayout”的listview(Recyclerview)。然后动态地在适配器中创建FrameLayout并分配不同的id对于每个。将 Fragment 膨胀到 FrameLayout 并将此 FrameLayout 膨胀到 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)