Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position of ViewPager after rotating in Android

Tags:

android

I have a ViewPager. My FragmentPageAdapter returns the position of the Viewpager in the getItem() methode. But after rotating the Screen the methode returns no value. Why? If I understood it right, everytime you rotate the screen OnCreateView() is called, but why doesn't it return the value any more? Could someone point out how to solve this? Thank you

Edit: My FragmentPageAdapter:

public Fragment getItem(int position) {

   return Fragment_results.newInstance(position);
}

My Fragment:

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);
like image 622
Ahmad Avatar asked Sep 27 '12 13:09

Ahmad


1 Answers

The position is set to 0 upon creating of the ViewPager instance and whenever you set a new adapter. When onCreateView() is called, you're rebuilding the entire app essentially. In order to revert back to the position it was, you must first use onSavedInstanceState(Bundle savedInstanceState) and store the item position via the Bundle.

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

Then in onCreate, restore the viewPager's state like so:

if (savedInstanceState != null) {
  myViewPager.setCurrentItem(savedInstanceState.getInt("pageItem", 0));
}
like image 97
DeeV Avatar answered Nov 05 '22 05:11

DeeV