Fei*_* Qu 9 android android-listview android-fragments
我想为listview中的每个项目创建一个片段,因为我想将一些逻辑分开.我正在为每个项目使用视图持有者.如果视图不存在,我创建一个新片段并将其添加到容器中.
holder.mMyFragment = new MyFragment(mActivity, this);
mActivity.getSupportFragmentManager().beginTransaction().add(R.id.my_container, holder.mMyFragment).commit();
Run Code Online (Sandbox Code Playgroud)
同样对于每个项目,我调用holder.mMyFragment.setUi(dataSource,position)来根据数据源和位置设置片段的UI.
我遇到的问题是我在片段类的onCreateView方法中初始化片段的UI元素,但是当我将片段添加到项目时它不会被调用.所以后来当我调用setUi()使用片段中的一些UI元素时,它会抱怨NullPointerException.有没有人有建议?谢谢!
gun*_*nar 10
我想为listview中的每个项目创建一个片段,因为我想将一些逻辑分开.
不能使用片段列表项的看法,因为API不允许你- View和Fragment甚至不相关的,所以没有办法,你可以用它这样的.创建自定义视图并使用适配器getViewTypeCount并getView使用不同的列表项行为.
片段由Activity的FragmentManager或其他Fragments子FragmentManager管理; 列表项视图由ListView和ListAdapter管理.您可以在片段中使用ListView,但不能使用其他方式.
"有一个解决方案 ".
问题是,您不能像在上面的代码中那样将list 直接添加到 listview中具有相同"id" 的容器(FrameLayout).
该伎俩是,创建列表视图"的LinearLayout"的(Recyclerview).然后在适配器中动态创建FrameLayout并为每个ID分配不同的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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20110 次 |
| 最近记录: |