Get focused View from ViewPager
It is possible to save the currently active object (View, Fragment, ...) by overriding PagerAdapter.setPrimaryItem method. For example:
private View mCurrentView;@Overridepublic void setPrimaryItem(ViewGroup container, int position, Object object) { mCurrentView = (View)object;}
You have to register a listener to your ViewPager
:
pager.setOnPageChangeListener(new MyPageChangeListener());
You have to customize the listener by extending a stub listener:
private int focusedPage = 0;private class MyPageChangeListener extends ViewPager.SimpleOnPageChangeListener { @Override public void onPageSelected(int position) { focusedPage = position; }}
I found this by looking at the ViewPager.java source code in the compatibility library. I read that we can do more, for example catch onPageScrollStateChanged
.
To build the adapter, I used the code on this blog post. You might want to have a look.
You can add a tag to the created view in the instantiateItem method:
view.setTag(position);
Later you can access the current selected view by:
mPager.findViewWithTag(mPager.getCurrentItem());