Nuno
Nuno

Reputation: 525

Inflate a layout on a ViewPager fragment

I've a ViewPager that uses a FragmentPagerAdapter, with 3 pages on it, and what I want is to inflate a new fragment layout on the top of my middle fragment when a button is pressed.

This was what I tried:

MainActivity.java

 ...

 // Method that is called when the button is cliked
 public void buttonCliked(View view) {
    viewPager.setCurrentItem(5);
 }

 ...

MyAdapter.java

 public Fragment getItem(int i) {

    Fragment fragment = null;
    if(i == 0) {
        ...
    }
    else if(i == 1) {
        ..
    }
    else if(i == 2) {
        ..
    }
    else if(i == 5){
        fragment = MyFragment.newInstance("aa", "aa");
    }

    return fragment;
}

But basically what's happening is, when I pressed the button, the ViewPager slides to the new fragment instead of replacing it. Any ideas how can I make this work the way I want?

Summing up how can I inflate a new layout on the top of the select fragment in a ViewPager?

Thanks.

Upvotes: 0

Views: 1324

Answers (1)

fvink
fvink

Reputation: 50

getItem is called when the adapter needs to instantiate a new fragment, not everytime you swipe to show another fragment. The adapter saves created fragments in FragmentManager, so if I understand your question correcty I think that's where need to get your fragment from and replace it.

There are answers how to retrieve fragments like that here on SO. Link

Edit: As shown in this answer:

mFragmentManager.beginTransaction().remove(mFragment).commit();
mFragment = NewFragment.newInstance();
notifyDataSetChanged();

Upvotes: 1

Related Questions