Search code examples
androidorientation-changesandroid-pageradapter

Save state of EditText in PagerAdapter upon orientation change


I'm struggling to make my application retain text entered into EditText when device orientation is changed. In my activity class I use ViewPager + PagerAdapter (android.support.v4.view.PagerAdapter)

public class MyActivity extends Activity
{
    ViewPager viewPager;
    PagerAdapter adapter;
    ArrayList<LessonItemI> arrayOfItems;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.pager_main);

        viewPager = (ViewPager) findViewById(R.id.pager);
        adapter = new MyPagerAdapter(this, arrayOfItems);
        viewPager.setAdapter(adapter);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            //my code here
        }
    }
}

MyPagerAdapter is:

    public class MyPagerAdapter extends PagerAdapter
    {    
        private Context context;
        private ArrayList<LessonItemI> arrayOfItems;
        private LayoutInflater inflater;

        public MyPagerAdapter(Context context, ArrayList<ItemI> flag)
        {
            this.context = context;
            this.arrayOfItems = flag;
        }
    //overrided methods here
    @Override
    public Object instantiateItem(ViewGroup container, int position)
    {
        final ItemI currentItem = arrayOfItems.get(position);
        View itemView = null;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
}

I would try to use onRestoreInstanceState and onSaveInstanceState methos of MyActivity but I am not sure I can get EditText fields from adapter plus it breaks encapsulation of my adapter. I'm considering saveState and restoreState methods of PagerAdapter but saveState returns Parcelable. Do I have to create object implementing Parcelable to save state? Sounds terrible. Bundle would be much better but it is not allowed in PagerAdapter. Do you guys have any thoughts how to handle this?


Solution

  • I decided to use fragments and FragmentPagerAdapter instead of PagerAdapter. I use three kind of fragments but the whole number of screens in swipe view is abut 10. So, I use the same fragments with different content. To retain state of fragments when view is swiped I use viewPager.setOffscreenPageLimit(arrayOfItems.size());. To retain state of fragment on orientation change overrided method onSaveInstanceState

    @Override
    public void onSaveInstanceState(Bundle outState)    //when rotated
    {
        super.onSaveInstanceState(outState);
    
        outState.putString("myKey", "myValueToRetain");
    }
    

    and in onActivityCreated

    if (savedInstanceState != null)
    {
        String myValue = savedInstanceState.getString("myKey"); 
    }