如何在不破坏碎片的情况下实现Dynamic ViewPager?

时间:2016-09-18 15:08:32

标签: java android android-viewpager

我正在使用viewPager,但它是动态的,即片段的位置不固定。它将根据服务器的响应进行更改。我不希望我的碎片被摧毁,我想保存他们的状态,但我无法做到这一点。我没有发布所有代码,只有必要的部分。拜托,我需要帮助...

P.S。我已经尝试过viewPager.setOffscreenPageLimit()。我可以用它保存状态,但只有一个片段一次又一次地被创建。

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Begin(), "Begin");
    questions = db.getAllQuestions();
    for (int i = 0; i <= questions.size() - 1; i++) {
        maxFrag = maxFrag + 1;
        type = questions.get(i).getType();
        title = String.valueOf(db.getQuestion(questions.get(i).getPK()).getTitle());
        if (type.equals("MCQ")) {
            adapter.addFragment(new MCQ(), "MCQ");
        } else if (type.equals("RATING")) {
            adapter.addFragment(new RATING(), "RATING");
        } else if (type.equals("MCQM")) {
            adapter.addFragment(new MCQM(), "MCQM");
        } else if (type.equals("CHARACTER")) {
            adapter.addFragment(new CHARACTER(), "CHARACTER");
        } else if (type.equals("TEXT")) {
            adapter.addFragment(new TEXT(), "TEXT");
        } else if (type.equals("NUMBER")) {
            adapter.addFragment(new NUMBER(), "NUMBER");
        }

    }
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(4);

    SharedPreferences sp = getSharedPreferences(SharedPreference.Feedback.COUNT, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putInt("count", maxFrag);
    editor.commit();

}

类适配器:

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

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

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}

@Override
public void onBackPressed() {
    int i = viewPager.getCurrentItem();
    if (i == 0) {
        finish();
    } else {
        viewPager.setCurrentItem(i - 1);
    }
}

0 个答案:

没有答案