0

Я использую ViewPager/FragmentPagerAdapter в одном из своих фрагментов приложения для отображения различных ListViews на каждой странице (см рисунок ниже): enter image description hereViewPager не показывать содержание страницы/не обновляется после изменения вида

Проблема заключается в том что после я изменить текущее представление (фрагмент), и я вновь открыть его снова, то ListView не отображается (см рисунок ниже):

enter image description here

поведение является случайным, иногда ListView показаны, когда я скользить между различными t абс/страницы.

Вот мой фрагмент кода:

public class AstucesFragment extends Fragment implements ActionBar.TabListener { 

    ActionBar actionBar; 
    AppSectionsPagerAdapter mAppSectionsPagerAdapter; 

    ViewPager mViewPager; 
    public static String[] tabslist = new String[5]; 

    public AstucesFragment() { 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View view = inflater.inflate(R.layout.fragment_astuces, container, false); 

     tabslist[0] = getActivity().getResources().getString(R.string.astuces_quotidien); 
     tabslist[1] = getActivity().getResources().getString(R.string.astuces_resto); 
     tabslist[2] = getActivity().getResources().getString(R.string.astuces_loisirs); 
     tabslist[3] = getActivity().getResources().getString(R.string.astuces_transports); 
     tabslist[4] = getActivity().getResources().getString(R.string.astuces_tous); 

     mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getActivity().getSupportFragmentManager()); 

     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

     mViewPager = (ViewPager) view.findViewById(R.id.astuces_pager); 
     mViewPager.setAdapter(mAppSectionsPagerAdapter); 
     mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
      @Override 
      public void onPageSelected(int position) { 
       actionBar.setSelectedNavigationItem(position); 
      } 
     }); 

     actionBar.addTab(
       actionBar.newTab() 
         .setCustomView(R.layout.fragment_astuces_tabs_quotidien) 
         .setTabListener(this)); 

     actionBar.addTab(
       actionBar.newTab() 
         .setCustomView(R.layout.fragment_astuces_tabs_resto) 
         .setTabListener(this)); 

     actionBar.addTab(
       actionBar.newTab() 
         .setCustomView(R.layout.fragment_astuces_tabs_loisirs) 
         .setTabListener(this)); 

     actionBar.addTab(
       actionBar.newTab() 
         .setCustomView(R.layout.fragment_astuces_tabs_transports) 
         .setTabListener(this)); 

     actionBar.addTab(
       actionBar.newTab() 
         .setCustomView(R.layout.fragment_astuces_tabs_tous) 
         .setTabListener(this)); 

     return view; 
    } 



    @Override 
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
     mViewPager.setCurrentItem(tab.getPosition()); 
     Log.i("AstucesFragment","onTabSelected()"); 
    } 

    @Override 
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 

    } 

    @Override 
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
     mViewPager.setCurrentItem(tab.getPosition()); 
     Log.i("AstucesFragment","onTabReselected()"); 
    } 


    /** 
    * A {@link android.support.v4.app.FragmentPagerAdapter} that returns a fragment corresponding to one of the primary 
    * sections of the app. 
    */ 
    public static class AppSectionsPagerAdapter extends FragmentPagerAdapter { 


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

     @Override 
     public Fragment getItem(int i) { 
      Log.i("AppSectionsPagerAdapter","Page ID : "+i); 
      // The other sections of the app are dummy placeholders. 
      Fragment fragment = new AstucesListFragment(); 
      Bundle args = new Bundle(); 
      args.putString(AstucesListFragment.ARG_PAGE_CAT, tabslist[i]); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     @Override 
     public int getCount() { 
      return tabslist.length; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      return tabslist[position]; 
     } 

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

    /** 
    * A dummy fragment representing a section of the app, but that simply displays dummy text. 
    */ 
    public static class AstucesListFragment extends Fragment { 

     public static final String ARG_PAGE_CAT = "page_cat"; 

     private List<Astuce> astuceList = new ArrayList<Astuce>(); 
     private ListView listView; 
     private AstuceAdapter adapter; 
     private AstuceDAO astuceDAO; 

     public AstucesListFragment() { 

     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
           Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_astuces_page, container, false); 
      Bundle args = getArguments(); 

      Log.i("AstucesListFragment","onCreateView()"); 


      String theme = ""; 
      if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_quotidien)) theme = "Q"; 
      else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_resto)) theme = "R"; 
      else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_loisirs)) theme = "L"; 
      else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_transports)) theme = "T"; 
      else theme = ""; 


      astuceDAO = new AstuceDAO(); 
      astuceList = astuceDAO.findAstuceByTheme(theme); 

      listView = (ListView) rootView.findViewById(R.id.astuces_list); 
      adapter = new AstuceAdapter(getActivity(), astuceList); 
      listView.setAdapter(adapter); 
      adapter.notifyDataSetChanged(); 


      return rootView; 
     } 
    } 

} 

Как я могу исправить эту проблему?

ответ

4
  1. Если вы хотите, чтобы ваши фрагменты сохранять свое состояние даже после изменения вкладки, Попробуйте это,

    mViewPager.setOffscreenPageLimit (5); // как у вас есть 5 фрагментов

Но это сделает операцию инициализацией всех фрагментов одновременно с действием.

  1. Другим методом является использование FragmentStatePagerAdapter вместо FragmentPagerAdapter. См,

http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html

+0

Я пробовал оба: - mViewPager.setOffscreenPageLimit (5); - FragmentStatePagerAdapter и он работает, спасибо! –

0

Вы не сравнения строк правильно. При сравнении двух строк вам нужно использовать метод equals() вместо оператора ==. Таким образом, в onCreateView() в AstucesListFragment заменить

if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_quotidien)) theme = "Q"; 
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_resto)) theme = "R"; 
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_loisirs)) theme = "L"; 
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_transports)) theme = "T"; 
else theme = ""; 

с

if (args.getString(ARG_PAGE_CAT).equals(getString(R.string.astuces_quotidien))) theme = "Q"; 
else if (args.getString(ARG_PAGE_CAT).equals(getString(R.string.astuces_resto))) theme = "R"; 
else if (args.getString(ARG_PAGE_CAT).equals(getString(R.string.astuces_loisirs))) theme = "L"; 
else if (args.getString(ARG_PAGE_CAT).equals(getString(R.string.astuces_transports))) theme = "T"; 
else theme = ""; 

это может решить вашу проблему, так как результаты операторов == будут несовместимы, поскольку обе эти строки могут или не могут указывать на тот же объект.