我有一个带有Framelayout和BottomNavigationView的活动......我有4个片段(A,B,C,D)......当我点击要加载的菜单项后从A切换到B时片段B,片段A被破坏...我在片段生命周期中涉及的所有回调方法(OnAttach,OnCreate,OnCreateView .....等)上添加了一条Log消息,当我更改片段时,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;
}
}
我想知道实际上我在这里失踪了什么......提前致谢
答案 0 :(得分:1)
好吧,你没有将片段添加到后台堆栈。
答案 1 :(得分:1)
您每次点击都会创建新实例。
如果你想用同一个替换那些,请保留对那些的引用或者然后添加到fragmentransaction的backstack,但是你需要使用标签来导航以前的那些。
答案 2 :(得分: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);
}