0

我有一個Framelayout和BottomNavigationView的活動...我有4個片段(A,B,C,D)......事情是當我從A到B後,點擊菜單項加載片段B,片段A被破壞......我在所有涉及Fragment生命週期和onDestroyView的回調方法(OnAttach,OnCreate,OnCreateView .....等)上添加了一條日誌消息是當我改變片段總是叫......所以,當我回來之前打開的片段,onCreateView被再次打電話..片段被重新創建後bottomnavigationview更改項目點擊

這裏是我的活動類:

public class Home extends AppCompatActivity 
{ 
    private BottomNavigationView.OnNavigationItemSelectedListener 
mOnNavigationItemSelectedListener 
     = new BottomNavigationView.OnNavigationItemSelectedListener() { 

    @Override 
    public boolean onNavigationItemSelected(@NonNull MenuItem item) 
    { 
     Fragment fragment = null; 
     Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); 
     switch (item.getItemId()) 
     { 
      case R.id.navigation_a: 
       if (!(currentFragment instanceof FragmentA)) 
        fragment = FragmentA.newInstance(); 
       break; 
      case R.id.navigation_b: 
       if (!(currentFragment instanceof FragmentB)) 
        fragment = FragmentB.newInstance(); 
       break; 
      case R.id.navigation_c: 
       if (!(currentFragment instanceof FragmentC)) 
        fragment = FragmentC.newInstance(); 
       break; 
      case R.id.navigation_d: 
       if (!(currentFragment instanceof FragmentD)) 
        fragment = FragmentD.newInstance(); 
       break; 
     } 

     if (fragment != null) { 
      getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit(); 
      return true; 
     } 

     return false; 
    } 

}; 


//TODO Handle life-cycle methods when switching between fragments 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_home); 
    Toolbar toolbar = findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    FragmentManager fm = getSupportFragmentManager(); 
    fm.beginTransaction() 
      .add(R.id.fragment_container, FragementA.newInstance()) 
      .commit(); 
    fm.popBackStack(); 

    BottomNavigationView navigation = findViewById(R.id.navigation);  navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); 
} 

public boolean onKeyDown(int keyCode, KeyEvent event) 
{ 
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    { 
     moveTaskToBack(true); 
     return true; 
     } 

    return false; 
    } 

} 

我想知道我在這裏實際上錯過了什麼....在此先感謝

+0

@Claude ...你有沒有想過它? – GvSharma

+0

@GvSharma ....我真的很抱歉我遲到的隊友!! ...其實我用了一個viewpager裏面..我沒有時間來測試下面提出的想法,因爲我在匆忙中..但我確實認爲將這個片段添加到後臺絕對可以解決這個問題.... –

回答

0

嘗試使用setRetainInstance(true);爲您的片段。

// this method is only called once for this fragment 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // retain this fragment 
    setRetainInstance(true); 
} 
+0

是的......其實我已經在我的問題發佈之前嘗試過了......似乎沒有這樣做 –

1

以及你不添加片段到後臺。

1

您正在每次點擊創建新實例。

如果您想用同一個替換或者添加到fragmentransaction的後臺堆棧,請保留對這些引用的引用,但是您需要用於導航到前一個的標籤。

相關問題