M
M
Makhach Imangazaliev2016-03-01 13:31:34
Android
Makhach Imangazaliev, 2016-03-01 13:31:34

How to insert an unusual fragment in ViewPager?

How to insert an unusual fragment in ViewPager?
There is a ViewPager with fragments. The adapter takes data from an array and fragments are created based on this array:

/**
 * Адаптер для ViewPager с шагами
 */
public class StepsAdapter extends FragmentStatePagerAdapter {

    private List<StepsMenuItem> mSteps;

    public StepsAdapter(FragmentManager fm, List<StepsMenuItem> steps) {
        super(fm);
        mSteps = steps;
    }

    @Override
    public Fragment getItem(int position) {
        return StepFragment.newInstance(mSteps.get(position).getFileName());
    }

    /**
     * Возвращает количество шагов
     *
     * @return Количество шагов
     */
    @Override
    public int getCount() {
        return mSteps.size()+1;
    }


}

Imagine that there are 10 elements in an array. I need to show at position 8 not the StepFragment fragment, but the WhatNextFragment fragment, while the rest of the fragments should move. In total, 11 elements are obtained. How can this be done most painlessly and with the fewest crutches?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2016-03-01
@ImangazalievM

You can do this:
Some interface:

interface Item {
    Fragment getFragment()
}

and two implementations:
class StepItemImpl implements Item {
    private StepsMenuItem data;
    StepItemImpl(StepsMenuItem data) {
        this.data = data;
    }
    @Override
    public Fragment getFragment() {
        return StepFragment.newInstance(data.getFileName());
    }
}

class WhatNextImpl implements Item {
    @Override
    public Fragment getFragment() {
        return WhatNextFragment.newInstance(...);
    }
}

further, you wrap your data in this class and you get a list:
List<Item> mItems;
...
    @Override
    public Fragment getItem(int position) {
        return mItems.get(position).getFragment();
    }
...
    @Override
    public int getCount() {
        return mItems.size()+1;
    }
/code>
Как-то так.

I
Ilya Pavlovsky, 2016-03-01
@TranE91

You can make your own analog getItemType (int position) as in the classic adapter from ListView

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question