如何获取ViewPager的当前视图,这是onPageSelected中用户的一个节目

时间:2016-04-15 05:42:01

标签: android android-viewpager android-pageradapter

我用这种方式获取ViewPager的当前视图:

private class OuterAdapter extends PagerAdapter{

    private SwipingVideoPage currentPage;

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        SwipingVideoPage page = new SwipingVideoPage();
        container.addView(page);
        return page;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        currentPage = (SwipingVideoPage)object;
        super.setPrimaryItem(container, position, object);
    }

    public SwipingVideoPage getCurrenPage() {
        return currentPage;
    }
}

我想我可以致电ViewPager.getAdapter.getCurrentPage()获取当前视图。但我发现它在ViewPager.OnPageChangeListener.onPageSelected()中无效:

private class OuterChangeListener implements ViewPager.OnPageChangeListener {

    @Override
    public void onPageSelected(int position) {
        ((OuterAdapter)outerViewPager.getAdapter()).getCurrenPage()  //this returns the previous shown view, not the right one
    }
}

也许在onPageSelected()之前调用setPrimaryItem(),这是正确的吗?

如何在ViewPage中获取onPageSelected()的主要观点?

2 个答案:

答案 0 :(得分:4)

正如@Mohammad Fareed所说,我没有找到一种方法直接在ViewPager中获取当前页面。

所以我用这种方式来解决问题:

private Map<Integer, View> pageMap;     //records all the pages in the ViewPager
private SwipingVideoPage currentPage;

private class OuterAdapter extends PagerAdapter{

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        SwipingVideoPage page = new SwipingVideoPage();
        container.addView(page);
        pageMap.put(position, page);    //add page
        return page;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
        pageMap.remove(position);      //remove page which is removed from ViewPager
    }
}

private class OuterChangeListener extends ViewPager.SimpleOnPageChangeListener {

    @Override
    public void onPageSelected(int position) {
        currentPage = pageMap.get(position);    //get current page
    }
}

我在我的项目中使用这些代码,直到现在它都运行良好。

答案 1 :(得分:-2)

在最新的套餐中你也可以使用

vp.getCurrentItem()

vp is the viewPager ,

pageListener = new PageListener();
vp.setOnPageChangeListener(pageListener);

您必须为viewPager添加页面更改侦听器。 viewPager上没有方法来获取当前页面。

private int currentPage;

private static class PageListener extends SimpleOnPageChangeListener{
        public void onPageSelected(int position) {
            Log.i(TAG, "page selected " + position);
               currentPage = position;
    }
}