仅更新ViewPager中的当前页面

时间:2014-07-19 09:57:44

标签: java android android-fragments android-viewpager

使用ViewPager。要为适配器PageStateAdapter提供方法notifyDataSetChanged(),请更新所有页面。它如何只更新ViewPager中的当前页面?

onCreateView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myView = inflater.inflate(R.layout.my_layout, container, false);
    MyPageAdapter myAdapter = new MyPageAdapter(getChildFragmentManager(), true);
    ViewPager myPager = (ViewPager) myView.findViewById(R.id.my_pager);
    myPager.setAdapter(myAdapter);
    myPager.setCurrentItem(0);
}

PageAdapter:

//
    private class MyPagerAdapter extends FragmentStatePagerAdapter {
        private MyFragment[] fragments;


        public MyPagerAdapter(FragmentManager fm) {
            super(fm);

            fragments = new MyFragment[] { new Fragment1(), new Fragment2(), new Fragment3() };
        }

        @Override
        public Fragment getItem(int i) {
            return fragments[i];
        }

        @Override
        public int getCount() {
            return fragments.length;
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {

        }
    }
//

1 个答案:

答案 0 :(得分:0)

要在addTab()课程中找到当前页面添加adapter方法。在该方法中设置Tag.

   public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
        TabInfo info = new TabInfo(clss, args);
        tab.setTag(info);
        tab.setTabListener(this);
        mTabs.add(info);
        mActionBar.addTab(tab);
        notifyDataSetChanged();
    }

然后在TabSelected上,您可以查看Tag

   @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        Object tag = tab.getTag();
        for (int i=0; i<mTabs.size(); i++) {
            if (mTabs.get(i) == tag) {
                mViewPager.setCurrentItem(i);
            }
        }
    }

有关详情,请访问thisthis链接