(I figured out a solution - please see my post in the Answer section below.)
In my app, the user will start with a single view of his data. I'd like to add a ViewPager and allow the user to add more views as desired. How do I do this? (I dont' want to use the FragmentPagerAdapter.)
I've read countless posts and overviews but am still missing something. Here's what I think I understand:
MainActivity creates a ViewPager and PagerAdapter:
ViewPager pager = null;
MainPagerAdapter adapter = null;
public void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
pager = new ViewPager (this);
setContentView (pager);
adapter = new MainPagerAdapter();
pager.setAdapter (adapter);
View v0 = code_to_create_initial_view();
adapter.add (v0, 0);
}
Use a PagerAdapter to provide the sets of view. For this it seems I need methods to add and remove views, something like this; obviously more is needed to tell the ViewPager stuff has changed and how to show the change:
class MainPagerAdapter extends PagerAdapter
{
// This holds all the currently displayable views, in order from left to right.
private ArrayList<View> views = new ArrayList<View>();
public void addView (View v, int position)
{
views.add (position, v);
}
public void removeView (int position)
{
views.remove (position);
}
}
In addition, I need to implement the following vitual methods. I'm lost here - what calls them and what are they supposed to do (ok, getCount is obvious)?
public object instantiateItem (ViewGroup pager, int position);
public void destroyItem (ViewGroup, int, Object);
public int getCount ();
public boolean isViewFromObject (View, Object);
- What are the ViewGroup params for - isn't the containing group the ViewPager itself?
- What does isViewFromObject do - how does an object get associated with a view in the first place?
- Should I be calling startUpdate and finishUdate when I add or remove views?
Thanks.
To remove you can use this directly:
fragment
is the fragment you want to remove.I've created a custom PagerAdapters library to change items in PagerAdapters dynamically.
You can change items dynamically like following by using this library.
Thils library also support pages created by Fragments.