我有一個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;
}
}
我想知道我在這裏實際上錯過了什麼....在此先感謝
@Claude ...你有沒有想過它? – GvSharma
@GvSharma ....我真的很抱歉我遲到的隊友!! ...其實我用了一個viewpager裏面..我沒有時間來測試下面提出的想法,因爲我在匆忙中..但我確實認爲將這個片段添加到後臺絕對可以解決這個問題.... –