Get focused View from ViewPager

后端 未结 11 1214
情深已故
情深已故 2020-11-27 12:50

i use the ViewPager for switching views with left/right swipe.

The ViewPager needs an Adapter, so I\'ve built this one:

public class ListViewPagerAda         


        
相关标签:
11条回答
  • 2020-11-27 13:40

    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());
    
    0 讨论(0)
  • 2020-11-27 13:42

    Am I missing something? There's only ever 3 children inside the ViewGroup, so it boils down to:

    int current = viewPager.getCurrentItem();
    int childCount = viewPager.getChildCount();
    // If there's a single page or we're at the beginning, return the first view
    if (childCount == 1 || current == 0) {
      return viewPager.getChildAt(0);
    } else { //For any other case, we want the second child. This is either the last page or the page in the middle for any other case.
      return viewPager.getChildAt(1);
    }
    
    0 讨论(0)
  • 2020-11-27 13:43

    Inside your FragmentStatePagerAdapter:

        private View mCurrentView;
    
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            Fragment f = (Fragment) object;
            mCurrentView = f.getView();
        }
    
    0 讨论(0)
  • 2020-11-27 13:49

    You can use:

     viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
            }
    
            @Override
            public void onPageSelected(int position) {
                Log.i("maylonsales", "onPageSelected position " + position);
            }
    
            @Override
            public void onPageScrollStateChanged(int state) {
    
            }
        });
    
    0 讨论(0)
  • 2020-11-27 13:50

    Try this:

    public View getCurrentView(ViewPager pager) {
        for (int i = 0; i < pager.getChildCount(); i++) {
            View child = pager.getChildAt(i);
            if (child.getX() <= pager.getScrollX() + pager.getWidth() && 
                child.getX() + child.getWidth() >= pager.getScrollX() + pager.getWidth()) {
                return child;
             }
         }
         return getChildAt(0);
    }
    
    0 讨论(0)
提交回复
热议问题