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

后端 未结 5 424
北恋
北恋 2020-12-05 17:54

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

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

retu

相关标签:
5条回答
  • 2020-12-05 18:33

    Add tag to Viewpager return view.

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

    0 讨论(0)
  • 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()

    0 讨论(0)
  • 2020-12-05 18:34

    Your view pager adapter is holding maximum of 2 pages, i.e 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()

    0 讨论(0)
  • 2020-12-05 18:50

    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).

    0 讨论(0)
  • 2020-12-05 18:50

    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.

    0 讨论(0)
提交回复
热议问题