简体   繁体   中英

RecyclerViewAdapter to New Fragment Transaction

I have written in Code Section

Main Activity, In Main Activity, there are 3 Fragments, fragments 1, 2 & 3.

In the fragments 1, I'm showing a Text and some Images from an URL by Using a RecyclerView adapter. The total number of Texts and Images is 27 items. It means item1(text1, image1) , item2(text2, image2) ... itemN(textN, imageN)

So I want to set an OnClickListener that works for

//this is pseudo-code
if (text1 is clicked) 
{
    goto NEW FRAGMENT1;
}
if (text2 is clicked)
{
    goto NEW FRAGMENT2;
}

So let's talk about the code, in my RecyclerView I'm Successfully able to identify which item is clicked. My only problem is, I was unable to transfer from RecyclerView to new Fragment . In the getSupportFragmentManager or getFragmentManager I'm getting an error.

A Sample Code of my code:

viewHolder.item_shows.setOnClickListner(new View.OnCliclListner(){
@Override
public void onClick (View view)
{
String itemPosition = String.valueOf(viewHolder.getAdapterPosition());
// item position works fine. Its shows which number item clicked.
// ******** HELP **********}}};
return viewHolder;
--------------------
//In ******** HELP ********** this position I want to create
if(iemPosition.equals("0"))
{open New Fragment1}
if(itemPosition.equals("1"))
{open New Fragment2}

You need to pass reference of your activity in constructor of adapter. Because getSupportFragmentManager() is method of activity class not your adapter class.

class MyAdapter(Activity mActivity,ArrayList<Model> list){

}

so use it like below to replace fragment in your activity container.

mActivity.getSupportFragmentManager()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM