Mert Serimer
Mert Serimer

Reputation: 1245

ViewPager and Fragments Issue

Lets assume i have three fragments inside viewPager adapter.

Does it create view (on create view called) every time i scroll to that fragment

OR

is it called only in initialization in main activity when we try to set adapter?

If it is the second, then heavy work will be done at the beginning. If it is first, then i have to save fragments states and must not call its init methods all the time.

Thanks in advance.

    List<Fragment> l = new ArrayList<>();
    l.add(Fragment.instantiate(this, DashBoard.class.getName()));
    l.add(Fragment.instantiate(this,Expenses.class.getName()));
    l.add(Fragment.instantiate(this,Gross.class.getName()));
    SliderAdapter sa = new SliderAdapter(getSupportFragmentManager(),l);
    vp = (ViewPager) findViewById(R.id.viewPager);
    vp.setAdapter(sa);

Upvotes: 2

Views: 502

Answers (2)

K Guru
K Guru

Reputation: 1302

No , its not create every time you swipe left or right .it keeps additional pages .but you can create it every time by setting off screen page limits .

public void setOffscreenPageLimit (int limit)

for Reference please check this

Upvotes: 1

KOTIOS
KOTIOS

Reputation: 11196

Yes the onCreteView is called everytime you swipe th fragments

Solution : One of the solution can be using :

public void setOffscreenPageLimit (int limit) api

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed. refer Android Doc

Upvotes: 1

Related Questions