Getting Parent ViewPager View from inside Fragment
Edit: I must add, even though Eldhose answer's works, I would defend my approach. Because the less the fragment knows about the Activity containing it, the better. By doing this, you can get the parent view without depending on IDs, and you can still get information from it even if it isn't a ViewPager.
You can get the in the Fragment's onCreateView
method.
The container
param is the parent View, in that case, a ViewPager.
In Java:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewPager pager = (ViewPager) container;
//.... Rest of your method
}
Kotlin Version:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup,
savedInstanceState: Bundle) {
val pager = container as ViewPager
//.... Rest of your method
}
The methods onCreateView
and onViewCreated
and onAttach
are called too early.
The view is definitely attached to its parent view in the fragment's onResume
method. This is a good place to then use getView().getParent()
From fragment, call getActivity() which will gives you the activity in which the fragment is hosted. Then call findViewById(ViewPagerId) to get the ViewPager.
ViewPager vp=(ViewPager) getActivity().findViewById(ViewPagerId);