from the adapter of a RecyclerView which is contained in an Activity, i\'m trying to launch a fragment when an element of the RecyclerView is pressed, this is my code right
If you are using a Sections Pager Adapter, the simple thing to do would be using an onclick on image view or button like below:
In your starting activity (from where you want to go) use put extra to send some information to another activity
ivPhotoAlbums.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Send The Message Receiver ID & Name
Intent intent = new Intent(v.getContext(), PhotosActivity.class);
intent.putExtra("viewpager_position", 1);
v.getContext().startActivity(intent);
}
});
In your activity in which you want to land (at the end of your setupViewPager() function) catch that extra and use it as position
int position = 0;
Bundle extras = getIntent().getExtras();
if (extras != null) {
position = extras.getInt("viewpager_position");
}
viewPager.setCurrentItem(position);
Given the Assumption that your setupViewPager() function looks like below in your destination activity
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FriendsAlbumsFragment()); //index 0
adapter.addFragment(new MyAlbumsFragment()); //index 1
adapter.addFragment(new AddPhotosFragment()); //index 2
final ViewPager viewPager = findViewById(R.id.l_center_view_pager_view_pager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.l_top_tabs_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_friends_photos);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_my_photos);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_add_photos);
And Your SectionsPagerAdapter class looks like below (separate public class)
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List mFragmentList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
return mFragmentList.get(i);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
}
And your center view pager layout is
Included in another file like this (or not included - in my case it was included)
This will take you right from an activity to a fragment (in another activity) or from a fragment in one activity to a fragment in another activity...