Android ViewPager get the current View

I have a ViewPager, and I'd like to get the current selected and visible view, not a position.

  1. getChildAt(getCurrentItem) returns wrong View
  2. This works not all the time. Sometimes returns null, sometimes just returns wrong View.

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    
        if (isVisibleToUser == true) { 
            mFocusedListView = ListView; 
        }
    }
    
  3. PageListener on ViewPager with getChildAt() also not working, not giving me the correct View every time.

How can i get current visible View?

View view = MyActivity.mViewPager.getChildAt(MyActivity.mViewPager.getCurrentItem()).getRootView();
ListView listview = (ListView) view.findViewById(R.id.ListViewItems);

Solution 1:

I've figured it out. What I did was to call setTag() with a name to all Views/ListViews, and just call findViewWithTag(mytag), mytag being the tag.

Unfortunately, there's no other way to solve this.

Solution 2:

I just came across the same issue and resolved it by using:

View view = MyActivity.mViewPager.getFocusedChild();

Solution 3:

You can get the current element by accessing your list of itens from your adapter calling myAdapter.yourListItens.get(myViewPager.getCurrentItem()); As you can see, ViewPager can retrieve the current index of element of you adapter (current page).

If you is using FragmentPagerAdapter you can do this cast:

FragmentPagerAdapter adapter = (FragmentPagerAdapter)myViewPager.getAdapter();

and call

adapter.getItem(myViewPager.getCurrentItem());

This works very well for me ;)

Solution 4:

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;
    }