Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

android - Add fragment into listview item

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...