Reputation: 5212
I am trying find a solution simular this https://stackoverflow.com/a/13925130/1634451 but the poster didn't explain what R.id.products_list_linear is. I tried to set R.id.products_list_linear as the id of my linearlayout for the fragment i am trying to replace. But that just overlays the 2 fragments on top of each other. I am pretty sure that i need to get the id of the container in the viewpager but i don't know how to get this id.
Edit: To clarify i am trying to replace a fragment in a view pager with another my code looks almost exactly like the answer I posted but when I make R.id.products_list_linear the I'd of the fragment I am trying to replace layout. The fragment I am replacing just gets overlaid on the one I am trying to replace
Upvotes: 1
Views: 1916
Reputation: 6441
Replace Fragments Within a View Pager
Try this customized ViewPager Adapter,..
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments=null;
private FragmentManager fragmentManager=null;
public ViewPagerAdapter(FragmentManager fragmentManager,List<Fragment> fragments) {
super(fragmentManager);
this.fragments=fragments;
this.fragmentManager=fragmentManager;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
super.setPrimaryItem(container,0,object);
}
@Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
fragmentManager.executePendingTransactions();
fragmentManager.saveFragmentInstanceState(fragments.get(position));
}
public void replaceItem(int position,Fragment fragment)
{
fragments.set(position, fragment);
this.notifyDataSetChanged();
}
}
call it from activity with fragment as arguments,
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment4.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment5.class.getName()));
mPagerAdapter=new ViewPagerAdapter(getFragmentManager(), fragments);
When you replace view/fragment inside of viewPager then use,
mPagerAdapter.replaceItem(2,Fragment.instantiate(this, Fragment5.class.getName()));
Upvotes: 2
Reputation: 5212
I ended up going with a different approach that worked out nicely for me. I used a ViewSwitcher for the fragment in the viewpager.
Upvotes: 0