Monday, August 7, 2017

Android Create A Dynamic Fragment On ViewPager

Today i will show you how to add dynamic fragment in viewpager. Dynamic means the size of fragment can change everytime.

Example :

In a list there are 10 items, it means there will 10 fragments appears in viewpager. If there are 5 items, then 5 fragments will appears.


So for create a dynamic fragment on viewpager, please read carefully the following steps :

File Drawable

Inside folder drawable, create a new xml file that will used as indicator. Look the following image :

Indicator viewpager
Create the following xml file and place it insideres/drawable on your project :




This project use 2 layouts (1 for activity and 1 for fragment):
  1. activity_main.xml 
  2. fragment_dinamis.xml


This file contains viewpager and its indicator. here is the code :


This file contains attributes that will appears on fragment. Attributes will appears on fragment depend on its data in List. In this proheject i use textview as fragment's marker number (you can change as you wish). Here is the code :

Code in Class Java

In this part, we will use 3 java classes, they are :

This class is a fragment class. We just create on fragment class, other fragments will create automatically depend on list size. Here is the code :

There is not special code in fragment above, just like usual. The increment of fragment will happen in its adapter.

Take a look at method setDetail(). This method used in adapter, Why?

Because data got from activity, then data will sent to adapter, from adapter data will set into its fragment.

Take a look at attribute fragments. That attribute created as an array ([]), it because the size of data will dynamic, so the fragment also created dynamic (as an array).

Take a look again to method getItem(int position). There is a function : dinamisFragment.setDetail(items). Method setDetail() came from DinamisFragment.

In this file as usual is place where we set the data into a List, hosting the viewpager, etc. Here is the code :

That's all about how to create a dynamic fragment on viewpager. Hope it helps. Thank you.

Related Posts

1 komentar so far