2016-07-26 2 views
0

Я пытаюсь разработать приложение, чье требование сохранить Tab даже после закрытия приложения или внезапно, если приложение разрушается во время выполненияКак сохранить фрагмент после того, как App был разрушен или закрыт

Мое приложение имеет 3 вкладки, я добавляю элементы в secondtab «CheckList» Когда я закрываю вторую вкладку приложения снова с новой страницей вместо добавленных ранее позиций

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

Picture 1 http://i.stack.imgur.com/KSgTZ.png

Изображение 2 http://i.stack.imgur.com/oUim4.png

псевдопользователей Код:

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); 

    } 

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

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

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

ответ

0

Вы не можете сохранить Fragment экземпляр ,

Вместо этого вы должны сохранить & восстановить состояние Fragment s. (например, с использованием SharedPreferences)

Смежные вопросы