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
580 views
in Technique[技术] by (71.8m points)

android - How to call getFragmentManager on Recycler.Adapter?

I am converting ListView of my app to RecyclerView. On ListView, it was very easy to implement OnClickListener but in RecyclerView, we have to do it in adapter. I want to open a new Fragment when user clicks on a item. To do this I have to call FragmentManager in adapter which I am not able to do. This is my code of RecyclerAdapter:

public ListItemViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
            description = (TextView) itemView.findViewById(R.id.description);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            //Call FragmentManager and add Fragment to it.
            }
        }

So, how to call FragmentManager and add Fragments in it. Is there any better way than this like sendingBroadcast or any other method.

question from:https://stackoverflow.com/questions/30866925/how-to-call-getfragmentmanager-on-recycler-adapter

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

1 Reply

0 votes
by (71.8m points)

You just need an activity context passed in your constructor. Be sure to call new Adapter(this,...) from activities and new Adapter(getActivity(),...) from fragments.

private Context context;

@Override
public void onClick(View v) {
    FragmentManager manager = ((AppCompatActivity)context).getSupportFragmentManager();
}

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

...