Замена фрагмента из ViewPager android

СЦЕНАРИЙ

Я создаю фрагментную структуру с динамическими созданиями фрагментов. Каждый элемент во фрагменте создает следующий фрагмент. В сценарии я храню все эти фрагменты в ArrayList фрагментов, чтобы я мог легко заменить созданный фрагмент.

ПРОБЛЕМА

Теперь я заменяю фрагмент из ArrayList, удаляя фрагмент из определенного индекса и добавляя новый. Но когда я пытаюсь получить фрагмент из этого конкретного индекса, он возвращает мне старые данные без повторного вызова функции getItem из FragmentStateAdapter.

Вот мой главный класс.

MainActivity.java

public class MainActivity extends FragmentActivity implements
    onPageSelectedListener {
SectionsPagerAdapter mSectionsPagerAdapter;
static int current, listItem;
static String TAG = "MainActivity";
static ViewPager mViewPager;
static ArrayList<Fragment> FragmentList;
static ArrayList<String> titles;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
}

public void init(){
    FragmentList = new ArrayList<Fragment>();
    titles = new ArrayList<String>();
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());
    mViewPager.setAdapter(mSectionsPagerAdapter);
}

public void addPage(int position, String title, String file, String tag) {
    Fragment fragment = new DummySectionFragment();
    Bundle args = new Bundle();
    args.putString(DummySectionFragment.ARG_FILE_NAME, file);
    args.putString(DummySectionFragment.ARG_FILE_TAG, tag);
    args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
    fragment.setArguments(args);
    titles.add(position, title);
    FragmentList.add(position, fragment);
}

public void NextScreen(int position, String title, String file, String tagname) {
    if(FragmentList.size()>(position-1)){
        for(int i=position; i<FragmentList.size(); i++){
            FragmentList.remove(i);
        }
    }
    addPage(position, title, file, tagname);
    mViewPager.setCurrentItem(position);

}

public static class PageChanger extends
        ViewPager.SimpleOnPageChangeListener {
    private int currentPage;

    @Override
    public void onPageSelected(int position) {
        currentPage = position;
    }

    public int getCurrentScreen() {
        return currentPage;
    }
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
        addPage(0, "Main Fragment", "test.xml", "mytag");
    }

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

    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        if (position == 0) {
            return "Main Categories";
        }
        getItem(position);
        return titles.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }


}
public static class DummySectionFragment extends Fragment {
    public static final String ARG_SECTION_NUMBER = "section_number";
    public static final String ARG_FILE_NAME = "file_name";
    public static final String ARG_FILE_TAG = "tag_name";

    public DummySectionFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        savedInstanceState = this.getArguments();
        ListView parent_list = new ListView(getActivity());
        String file_name = savedInstanceState.getString(ARG_FILE_NAME);
        String tag_name = savedInstanceState.getString(ARG_FILE_TAG);
        int current_level = savedInstanceState.getInt(ARG_SECTION_NUMBER);
        PullParser pull = new PullParser(getActivity());
        pull.pullXml(file_name, tag_name);
        parent_list.setAdapter(new ListAdapter(getActivity(),
                PullParser.Xml_Tag_Info, current_level));
        return parent_list;
    }
}

@Override
public void onPageSelected(int pageno) {
    current = pageno;
}
}

2 ответа

Решение

Я нашел ответ только для повторной установки адаптера после внесения необходимых изменений. Отредактированный код здесь.

MainActivity.java

public class MainActivity extends FragmentActivity {
    SectionsPagerAdapter mSectionsPagerAdapter;
    static int current, listItem;
    static String TAG = "MainActivity";
    static boolean flag = false;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    static ViewPager mViewPager;
    static ArrayList<DummySectionFragment> FragmentList;
    static ArrayList<String> titles;
    static FragmentManager fragManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init() {
        FragmentList = new ArrayList<DummySectionFragment>();
        titles = new ArrayList<String>();
        mViewPager = (ViewPager) findViewById(R.id.pager);
        fragManager = getSupportFragmentManager();
        mSectionsPagerAdapter = new SectionsPagerAdapter(fragManager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        titles.add(0, "Main Categories");
    }

    public void addPage(final int position, String file, String tag) {
        DummySectionFragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putString(DummySectionFragment.ARG_FILE_NAME, file);
        args.putString(DummySectionFragment.ARG_FILE_TAG, tag);
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
        fragment.setArguments(args);
        try {
            FragmentList.set(position, fragment);
        } catch (IndexOutOfBoundsException e) {
            FragmentList.add(position, fragment);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void destroyFragment(int position) {
        SectionsPagerAdapter pagerAdapter = (SectionsPagerAdapter) mViewPager
                .getAdapter();
        pagerAdapter.destroyItem(mViewPager, position,
                FragmentList.get(position));
        pagerAdapter.notifyDataSetChanged();
    }

    public void addFragment(int position, Object object) {
        SectionsPagerAdapter pagerAdapter = (SectionsPagerAdapter) mViewPager
                .getAdapter();
        pagerAdapter.notifyDataSetChanged();
    }

    public void NextScreen(int position, String title, String file,
            String tagname) {

        if (FragmentList.size() > position - 1) {
            for (int i = FragmentList.size() - 1; i > position; i--) {
                titles.remove(i);
                FragmentList.remove(i);
            }
            titles.trimToSize();
            FragmentList.trimToSize();
        }

        titles.add(position, title);
        addPage(position, file, tagname);
        mViewPager.setAdapter(new SectionsPagerAdapter(fragManager));
        mViewPager.setCurrentItem(position);
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            addPage(0, "catlist.xml", "pid-0");
        }

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

        }

        public void setId() {

        }

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

        @Override
        public int getItemPosition(Object object) {
            return FragmentList.indexOf(object);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Log.v("titlePosition", position + "");
            return titles.get(position);
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static ArrayList<Xml_Item_Data> resultList = new ArrayList<Xml_Item_Data>();
        public static final String ARG_SECTION_NUMBER = "section_number";
        public static final String ARG_FILE_NAME = "file_name";
        public static final String ARG_FILE_TAG = "tag_name";
        ListView parent_list;
        public static Bundle setValues;

        public DummySectionFragment() {

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            savedInstanceState = this.getArguments();
            parent_list = new ListView(getActivity());
            String file_name = savedInstanceState.getString(ARG_FILE_NAME);
            String tag_name = savedInstanceState.getString(ARG_FILE_TAG);
            int current_level = savedInstanceState.getInt(ARG_SECTION_NUMBER);
            PullParser pull = new PullParser(getActivity());
            pull.pullXml(file_name, tag_name);
            ListAdapter list_Creator = new ListAdapter(getActivity(),
                    PullParser.Xml_Tag_Info, current_level);
            parent_list.setAdapter(list_Creator);
            return parent_list;
        }
    }
}

Я думаю, что вы можете попробовать вернуть POSITION_NONE в вашем методе getItemPosition(). Как здесь: Как заставить ViewPager повторно создавать экземпляры своих элементов

Другие вопросы по тегам