Transfering data when changing ViewPager page in Android

   ViewPager is official widget for screen sliding in Android. By this component, tranfering data between it's Adapter/Fragment with it's activity is always a headache problem.
    In this tip, I will give a simple way to implement OnPageChangeListener interface to put data from ViewPager to Activity (update TextView and RatingBar status in Activity).

1. Declaring some xml files:

- Activity layout (activity_view_pager.xml):
- Fragment layout (fragment_view_pager.xml):

2. Programmatically coding:

- Create a model - implements Serializable to put through Bundle later (
- Customizing a ViewPager adapter (extends FragmentStatePagerAdapter):
- Programmatically code for each ViewPager Fragment:
- Activity coding:
* For "listening" ViewPager change page, we provide a onPageChangedListener method to get data from adapter  and update data in views (TextView and RatingBar):
* Events code of button Back and Next (change ViewPager's page):
Full code:
3. Result after build and run (click for full size):

pic name pic name
Note: in this tip, I have used Serializable Object to put data through Bundle. For understanding 2 ways putting data in Android, see this tutorial.


Previous post
« Prev Post
Next post
Next Post »