简体   繁体   中英

How do I get the child View of a ViewPager at a given item

I'll keep the question as short and simple as humanly possible.

View activeView = mViewPager.getChildAt(mViewPager.getCurrentItem());

returns the child view when the current item is 0 and 1. But if the current item is 2 it returns null . Why is that?

edit: Let me rephrase myself. How do I get the child View of a ViewPager at any given item position?

It turns out getChildAt(int) was not the right approach. What I did was retrieve the Adapter used in the ViewPager and found my views from there:

adapter = mViewPager.getAdapter();
Fragment fragment = adapter.getItem(mViewPager.getCurrentItem());

View activeView = fragment.getView();

As already noted the viewPager will only contain the current child and adjacent children(currentItem() +/- 1) unless otherwise specified through setOffscreenPageLimit()

Your view pager adapter is holding maximum of 2 pages, ie 2 views/fragments, the rest of them are recycled. In other case, what you did not mentioned is that you might have 2 pages/views in the ViewPager.

Please look at mViewPager.setOffscreenPageLimit()

Add tag to Viewpager return view.

Below link will help you : https://stackoverflow.com/a/20186828/1271891

During my endeavors to find a way to decorate android views I think I defined alternative solution for th OP's problem that I have documented in my blog . I am linking to it as the code seems to be a little bit too much for including everything here.

The solution I propose:

  • keeps the adapter and the view entirely separated
  • one can easily query for a view with any index form the view pager and he will be returned either null if this view is currently not loaded or the corresponding view.

(This question is very simple to this one in which I have posted the same answer ).

How many child views should the be?

Also a ViewPager doesn't have all childs loaded at the same time. Only the one it is showing and the next one. You can use mViewPager.setOffscreenPageLimit() to, for example 3 or 4, to 'preload' more items into the viewpager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM