I have a ViewPager, and I\'d like to get the current selected and visible view, not a position.
getChildAt(getCurrentItem)
returns wrong Vi
Try this
final int position = mViewPager.getCurrentItem();
Fragment fragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.rewards_viewpager + ":"
+ position);
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:
null
if this view is currently not loaded or the corresponding view.I use this method with android.support.v4.view.ViewPager
View getCurrentView(ViewPager viewPager) {
try {
final int currentItem = viewPager.getCurrentItem();
for (int i = 0; i < viewPager.getChildCount(); i++) {
final View child = viewPager.getChildAt(i);
final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) child.getLayoutParams();
Field f = layoutParams.getClass().getDeclaredField("position"); //NoSuchFieldException
f.setAccessible(true);
int position = (Integer) f.get(layoutParams); //IllegalAccessException
if (!layoutParams.isDecor && currentItem == position) {
return child;
}
}
} catch (NoSuchFieldException e) {
Log.e(TAG, e.toString());
} catch (IllegalArgumentException e) {
Log.e(TAG, e.toString());
} catch (IllegalAccessException e) {
Log.e(TAG, e.toString());
}
return null;
}
Please check this
((ViewGroup))mViewPager.getChildAt(MyActivity.mViewPager.getCurrentItem()));
else verify this link.
viewpager.getChildAt(0)
this always returns my currently selected view. this worked for me but I don't know-how.
I had to do it more general, so I decided to use the private 'position' of ViewPager.LayoutParams
final int childCount = viewPager.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = viewPager.getChildAt(i);
final ViewPager.LayoutParams lp = (ViewPager.LayoutParams) child.getLayoutParams();
int position = 0;
try {
Field f = lp.getClass().getDeclaredField("position");
f.setAccessible(true);
position = f.getInt(lp); //IllegalAccessException
} catch (NoSuchFieldException | IllegalAccessException ex) {ex.printStackTrace();}
if (position == viewPager.getCurrentItem()) {
viewToDraw = child;
}
}