Get ViewPager position after turning on Android

I have a ViewPager. My FragmentPageAdapter returns the position of the Viewpager in the getItem () method. But after turning the screen, the method does not return a value. What for? If I understand correctly, each time you rotate the screen, OnCreateView () is called, but why doesn’t it return a value anymore? Can someone point out how to solve this? thank you

Edit: My FragmentPageAdapter:

public Fragment getItem(int position) { return Fragment_results.newInstance(position); } 

My snippet:

 public static Fragment_results newInstance(int i) { Fragment_results fragment = new Fragment_results(); fragment.mContent = i +""; return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_result, null); ((TextView) view.findViewById(R.id.text)).setText(mContent); 
+4
source share
1 answer

The position is set to 0 when you create an instance of ViewPager and whenever you install a new adapter. When onCreateView() is called, you completely rebuild the entire application. To return to a position, you must first use onSavedInstanceState(Bundle savedInstanceState) and save the position of the position through the Bundle.

 @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("pageItem", myViewPager.getCurrentItem()); } 

Then in onCreate restore the state of the viewPager as follows:

 if (savedInstanceState != null) { myViewPager.setCurrentItem(savedInstanceState.getInt("pageItem", 0)); } 
+12
source

Source: https://habr.com/ru/post/1436616/


All Articles