4

I am working on an android application and using viewpager in a view. I am using PagerAdapter to show the views of tabs in viewpager. I have to add/remove some Tabs dynamically. When I am adding any tab along with it's view then instantiateItem function is being called and tab is getting added successfully. But When I remove any tab from viewpager then destroyItem function should be called but it is not getting called and the view of Tab is not getting removed. This the code which I am using to add/remove tabs.

public List<View> viewsList = new ArrayList();
public HashMap<Integer, View> GridViewList = new HashMap<>();

MyAdapter myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
viewPager.setOffscreenPageLimit(myAdapter.getCount() + 1);

    private class MyAdapter extends PagerAdapter {
    public MyAdapter() {
        super();
    }

    @Override
    public int getCount() {
        return viewsList.size();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View v = viewsList.get(position).rootView;
        container.addView(v, 0);
        return v;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object view) {
        container.removeView((View)view);
    }

    @Override
    public boolean isViewFromObject(View view, Object key) {
        return key == view;
    }
}

I am adding using the below method When I add any Tab along with it's view

View view = new View(); // I am making Custom View here
viewsList.add(view);
GridViewList.put(Id, view);
myAdapter.notifyDataSetChanged();

And When I remove any view, I use below method :

viewsList.remove(GridViewList.get(Id));
GridViewList.remove(Id);
myAdapter.notifyDataSetChanged();

But the destroyItem function is not being called when I remove any Tab and it's view from adapter in android. Please help me if someone have any idea about this.

Thanks a lot in advanced.

Prithniraj Nicyone
  • 5,021
  • 13
  • 52
  • 78

1 Answers1

2

Late to the party, but: you need to implement getItemPosition in order for destroyItem to be called. In this case, something like this should work:

@Override public int getItemPosition(Object itemIdentifier) {
  int index = viewsList.indexOf(itemIdentifiers);
  return index == -1 ? POSITION_NONE : index;
}
oldergod
  • 15,033
  • 7
  • 62
  • 88
Eric
  • 5,323
  • 6
  • 30
  • 35