Как сохранить фрагмент после того, как приложение было уничтожено или закрыто

Я пытаюсь разработать приложение, требование которого - сохранить вкладку даже после закрытия приложения или внезапно, если приложение будет уничтожено во время выполнения.

Мое приложение имеет 3 вкладки, я добавляю элементы во второй вкладке "Контрольный список". Когда я закрываю вторую вкладку своего приложения, она снова открывается новой страницей, а не элементами, добавленными ранее.

Я хочу, чтобы мое приложение было таким же, как на рисунке 2, даже после закрытия приложения, но кажется, что каждый раз, когда я закрываю вкладку приложения, появляется изображение 1

Фото 1

Изображение 2

Код Псуэдо:

public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {

    SectionsPagerAdapter mSectionsPagerAdapter;

    ViewPager mViewPager;
    public Fragment fragment;
    private FragmentActivity myContext;

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

        final ActionBar actionBar = getSupportActionBar();
        View viewActionBar = getLayoutInflater().inflate(R.layout.titlebar, null);
        ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
                ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.MATCH_PARENT
                );
        TextView textviewTitle = (TextView) viewActionBar.findViewById(R.id.mytext);
        textviewTitle.setText("Application");
        actionBar.setCustomView(viewActionBar, params);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);


        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch(position){
                case 0:
                    fragment = new FirstTab();
                    break;
                case 1:
                    fragment = new SecondTab();

                    break;
                case 2:
                    fragment = new ThirdTab();

            }
            return fragment;
        }

Код второй вкладки:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        if(view==null) {
            view = inflater.inflate(R.layout.tab2, container, false);
// retain this fragment


            bt = (ImageView) view.findViewById(R.id.imageview3);
            tl = (TableLayout) view.findViewById(R.id.table);


          public void onSaveInstanceState(Bundle savedInstanceState) {

        super.onSaveInstanceState(savedInstanceState);

    }

Я застрял здесь, подскажите, пожалуйста, как мне сохранить эту вкладку с помощью вышеуказанного метода и как сохранить?

Я видел несколько ответов, касающихся сохранения фрагмента, но это не решило мою проблему

Я новичок в разработке Android, пожалуйста, попробуйте помочь решить эту проблему

1 ответ

You cannot retain a Fragment пример.

Instead, you should persist & restore the Fragments state. (например, используя SharedPreferences)

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