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.

Result

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 :

selected_item.xml

nonselected_item.xml

Layouting


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

activity_main.xml

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

fragment_dinamis.xml

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 :
  1. DinamisFragment.java
  2. FragmentAdapter.java
  3. MainActivity.java
 
DinamisFragment.java

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.

FragmentAdapter.java

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.

MainActivity.java

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

Thanks thanks thanks a lot! Dynamic ViewPager is a smart idea and i was looking for how to fix my bug to do that. your project help me to fix it .. thanks ..


EmoticonEmoticon