2017-04-10 58 views
0

我有三個選項卡,在一個選項卡中我請求數據表單後端。當再次點擊這個標籤時,它會重新加載。我想當我重新加載片段不重新創建,在內存中的所有東西在listView中。我的代碼是這樣的:如何保持選項卡中的狀態片段不重新加載?

 BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); 
     navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { 
     @Override 
     public boolean onNavigationItemSelected(@NonNull MenuItem item) { 
      Fragment fragment = null; 
      switch (item.getItemId()) { 
       case R.id.navigation_home: 
        fragment = FirstFragment.newInstance(); 
        break; 
       case R.id.navigation_dashboard: 
        fragment = SecondFragment.newInstance(); 
        break; 
       case R.id.navigation_notifications: 
        fragment = ThreeFragment.newInstance(); 
        break; 
      } 
      if (fragment != null) { 
       FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
       fragmentTransaction.replace(R.id.content, fragment); 
       fragmentTransaction.commit(); 
      } 

      return true; 
     } 
    }); 

但是,當我Symtems.print.out我看到的結果: - TAB1點擊

I/System.out: onCreate main 
    I/System.out: onAttach 1 
    I/System.out: onCreate 1 
    I/System.out: onCreateView 1 
    I/System.out: onResume main 
    I/System.out: onResume 1 

-Tab2點擊

I/System.out: onAttach 2 
I/System.out: onCreate 2 
I/System.out: onDetach 1 
I/System.out: onCreateView 2 
I/System.out: onResume 2 

-Reclick表1:

I/System.out: onAttach 1 
I/System.out: onPause 2 
I/System.out: onDetach 2 
I/System.out: onCreateView 1 
I/System.out: onResume 1 

wh en reclick a tabs all fragment lifecyle again again forfor我的代碼加載後端再次運行。當其他標籤點擊時,如何保持片段onPause,再次點擊時OnResume?

回答

0

您需要在您的片段裏面OnCreateView()添加此行

行添加

// check if view is null to avoid recreating 
if(rootView != null) { 
    return rootView; 
}else { 
    rootView = inflater.inflate(R.layout.fragment_film,container,false); 
} 
+0

我嘗試這個,但重新點擊標籤時,rootView allways null。 –

0

哦,我剛纔一直在你的地方。我做了什麼,我已經用擴展的ViewPager替代了BottomNavigationView,它關閉了滑動手勢。你可以在這裏找到它:How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

ViewPager有setOffScreenPageLimit(numberOfPages)方法,這將保持碎片的所需量從屏幕的兩側,以不重做所有的辛勤工作。

此外,使用簡單的TabLayout查看底部的標籤。

相關問題