我有一个带有 Framelayout 和一个 BottomNavigationView 的活动...我有 4 个片段(A、B、C、D)...问题是当我在单击菜单项以加载片段 B 后从 A 切换到 B 时,片段A被破坏......我在片段生命周期中涉及的所有回调方法(OnAttach,OnCreate,OnCreateView......等)上添加了一条日志消息,并且当我更改片段时总是调用onDestroyView......所以当我来的时候回到之前打开的片段,再次调用 onCreateView ..
这是我的活动课:
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;
}
}
我想知道我在这里实际上错过了什么......在此先感谢