在ViewPager中多次使用一个片段

Józ*_*sza 6 android dynamic fragment android-viewpager

是否可以多次在viewpager中使用一个片段?我正在尝试使用ViewPager构建动态更新的UI.我想使用相同的设计,基本上相同的片段,每个页面都有不同的数据,比如listview适配器.

Fra*_*kie 5

您可以为ViewPager中的每个页面实例化相同的Fragment类,并传递ViewPager的位置来控制显示内容。像这样:

public class MyFragment extends Fragment {

    private int mIndex;

    public MyFragment(int index) {
        mIndex = index;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

        switch(mIndex){
            case 0:
            // do you things..
            case 1:
            // etcetera
        }             
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的FragmentPagerAdapter中:

public static class MyAdapter extends FragmentPagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    @Override
    public Fragment getItem(int position) {
        return new MyFragment(position);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以重用大多数代码,仅更改switch / case语句中所需的内容。