如何访问FragPagerAdapter中的特定片段?

时间:2017-10-18 22:18:24

标签: android android-fragments android-adapter

我目前有一个FragmentPagerAdapter,它通过getItem(int position)方法创建每个Fragment的新实例。但是,我不太确定如何访问我再次创建的片段。是否有一个公共方法,另一个类可以从FragmentPagerAdapter调用,以选择在例如12位创建的特定片段?

public class ChannelFragmentAdapter extends FragmentPagerAdapter {
    private int numChannels;
    public ChannelFragmentAdapter(FragmentManager fm, Activity context, PatientSettings user) {
        super(fm);
        this.context = context;
        numChannels = user.channelsLimit;
        for(int i = 1; i <= numChannels; i++){
            channelTabs.add("" + i);
        }
    }

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

    @Override
    public Fragment getItem(int position) {
        //new instance is a static factory for creating Fragment objects
        return ChannelFragment.newInstance(position + 1, this);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        //generate title based on item position
        //return tabTitles[position];
        return  channelTabs.get(position);
    }
}

1 个答案:

答案 0 :(得分:1)

我想您正在尝试创建一个支持5个以上片段的viewpager,因此使用FragmentStatePagerAdapter会更好。

回到你的问题,使用Fragment标签并通过findFragmentByTag()进入。在适配器中,将它们存储在列表中,并在需要时随时获取它们。

public class ChannelFragmentAdapter extends FragmentPagerAdapter {
    private int numChannels;
    Map<Integer, String> tags;

    public ChannelFragmentAdapter(FragmentManager fm, Activity context, PatientSettings user) {
        super(fm);
        this.context = context;
        numChannels = user.channelsLimit;
        tags = new HashMap<>();
        for (int i = 1; i <= numChannels; i++) {
            channelTabs.add("" + i);
        }
    }

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

    @Override
    public Fragment getItem(int position) {
        //new instance is a static factory for creating Fragment objects
        return ChannelFragment.newInstance(position + 1, this);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        //generate title based on item position
        //return tabTitles[position];
        return channelTabs.get(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
        tags.put(position, createdFragment.getTag());
        // ... save the tags somewhere so you can reference them later
        return createdFragment;
    }
}

注意:使用findFragmentByTag()时请检查null,您的片段可能会被销毁或更换。