Understand how it works

You do not need to understand the nitty-gritty details in most cases but always better to understand how it works logically

The basic idea is that ViewPager keeps track of what page should be visible on screen and then asks the PagerAdapter to get View hierarchy that needs to be displayed

First, PagerAdapter create fragment 0 and 1
When you swipe from 0 to 1: keep fragment 0, create fragment 2
When you swipe from 1 to 2: detach fragment 0, create fragment 3
….
Basically, PagerAdater was designed to make sure that, right and left view always is ready to be shown at the time you swipe left or right.

PagerAdapter

FragmentPagerAdapter

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

FragmentStatePagerAdapter

This version of the pager is more useful when there are a large number of pages, working more like a list view.
When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved the savedInstanceState of fragments.
This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

How to transfer data activity <-> fragment, fragment <-> fragment

You probably just care about communication of the current visible fragment.
in my opinion, the most effective way is that you store all of fragment instances to a Hashmap then you can get fragment you want when you need.
Do not use interface as a callback in case many views use same fragment.java file
this is a common mistake and i will tell you why.
Now assume that we have viewpager with 5(or whatever) fragments inside a MainActivity
We use interface

public class MainActivity   {
public static ChangeTextListener listener;
}
public class ContentFragment extends ChangeTextListenner {
  MainActivity.listener = this

 overide 
 void changeText(String text){
//do something
}
}
public interface ChangeTextListener {
void changeText(String text)
}

We all know that at the time fragment 1 is visible, fragment 2 is created. Since that MainActivity.listener = fragment 2 (NOT FRAGMENT 1) and changeText(String text) in fragment 2 will be called meanwhile fragment 1 is shown. It’s doesn’t make sense in most cases

Be careful if you use static variable or method.
static variable/method belongs to the class and not to object(instance)

A nature, universe, science, music, love lover

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami