在ViewPager中多次使用一个片段 [英] Use one Fragment in a ViewPager multiple times

查看:166
本文介绍了在ViewPager中多次使用一个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to use one fragment in a viewpager multiple times? I am trying to build a dynamically updated UI using ViewPager. I want to use the same design, basically the same fragment with different data for every page, like a listview adapter.

推荐答案

您可以为ViewPager中的每个页面实例化相同的Fragment类,通过ViewPager的位置来控制显示的内容。类似的东西:

You can instantiate the same Fragment class for every page in your ViewPager, passing the position of the ViewPager to control what to display. Something like that:

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
        }             
    }
}

然后,您的FragmentPagerAdapter:

then, in you 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);
    }
}

这样,您可以重复使用大部分只更改代码在switch / case语句中需要什么。

That way you can reuse most of your code changing only what you need in the switch/case statement.

这篇关于在ViewPager中多次使用一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆