I have implemented a ViewPager with FragmentStatePagerAdapter and i want an ItemClickListener so that i can open the detail screen when the user clicks on each fragment of the viewpager. I am not able to find any such methods which are available.
-
https://stackoverflow.com/questions/16350987/viewpager-onitemclicklistener – duggu Jun 25 '18 at 16:39
2 Answers
You should implement a callback interface to communicate between your fragments and your containing activity. In each fragment, set your needed listeners, and then pass any information needed back to your activity to handle the click.
public class MyFragment extends Fragment {
public interface MyFragmentListener {
void onTheActivityICareAbout();
}
private MyFragmentListener mCallback;
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallback = (MyFragmentListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement MyFragmentListener");
}
}
}
Then when you bind your view, set your listner to use the callback on whatever event you need and your activity has your centralized code to handle that. Any interface method can also be used to pass data back to the activity as well.
You can see this link for more details.

- 800
- 6
- 10
-
-
-
Your activity just needs to implement the listener for the fragment. – Bryan Dormaier Feb 19 '21 at 02:31
Your FragmentStatePageAdapter will have a method that looks like this:
override fun getItem(day: Int): Fragment = YourPageFrament.newInstance()
So, in the code for YourPageFragment, you can set on OnClickListener on the fragment itself.
You can set this listener by modifying the XML layout file for that fragment to include a Linear Layout or some kind of layout.
Then, in your YourPageFragment class, possibly in your onCreateView() method, you can set on OnClickListener on the fragment's layout.