了解FrameStatePagerAdapter中的getItem()

时间:2015-10-21 11:18:01

标签: android fragmentstatepageradapter pagerslidingtabstrip

我正在尝试按照在线教程在我的应用中实现滑动标签。特别是this one

我想要实现的目标是:

基于单个MainActivity的带有滑动标签的Fragment。每个标签显示不同的数据。为此,我试图获取在我的片段中选择的选项卡的当前位置,但我似乎没有得到正确的值。我知道多次调用getItem()的函数,有时根本不调用。

那么如何获取片段中所选标签的当前位置?我链接的教程将位置值与getItem()的return语句一起传递,但由于我在日志和setText中获得了不同的值,因此似乎效果不佳。

getItem()

@Override
public Fragment getItem(int position) {
    return PageFragment.newInstance(position + 1);
}

PageFragment:

public static PageFragment newInstance(int page) {
    Bundle args = new Bundle();
    args.putInt(ARG_PAGE, page);
    PageFragment fragment = new PageFragment();
    fragment.setArguments(args);
    return fragment;
}

位置值差异:

position value fetched in onCreate of fragment

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,我决定彻底改变"默认" PagerAdapter这样我就不必自己处理position

/**
 * TabsPagerAdapter.
 *
 * @author Niels
 * @version 1.0
 * @since 11-9-2015
 */
public class TabsPagerAdapter extends FragmentPagerAdapter {

    /**
     * Contains all the fragments.
     */
    private List<Fragment> fragments = new ArrayList<>();

    /**
     * Contains all the tab titles.
     */
    private List<String> tabTitles = new ArrayList<>();

    /**
     * Creates a new PagerAdapter instance.
     *
     * @param fragmentManager The FragmentManager.
     */
    public TabsPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

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

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles.get(position);
    }

    /**
     * Adds the fragment to the list, also adds the fragment's tab title.
     *
     * @param fragment New instance of the Fragment to be associated with this tab.
     * @param tabTitle A String containing the tab title for this Fragment.
     */
    public void addFragment(Fragment fragment, String tabTitle) {
        fragments.add(fragment);
        tabTitles.add(tabTitle);
    }

}

您可以这样使用:

@Override
public void onCreate() {
    adapter = new TabsPagerAdapter(getSupportFragmentManager()); //TabsPagerAdapter = whatever you named the PagerAdapter
    addFragments();
    viewpager.setAdapter(adapter); //viewpager = ViewPager view instance
    strip.setViewPager(viewpager); //strip = PagerSlidingTabStrip view instance
}

/**
 * Adds fragments to the adapter.
 */
private void addFragments() {
    adapter.addFragment(new Fragment1(), "Fragment1");
    adapter.addFragment(new Fragment2(), "Fragment2");
    adapter.addFragment(new Fragment3(), "Fragment3");
    adapter.addFragment(new Fragment4(), "Fragment4");
}