在我的应用程序中,我使用三个片段活动用于导航抽屉,但是在使用片段事务替换一个片段时,总是显示最后一个片段为什么?这是我的代码: -
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new HomeFragment();
Class fragmentClass = null;
switch (position) {
case 0:
Log.d("position1", String.valueOf(position));
fragmentClass = FarecardFragment.class;
case 1:
Log.d("position1", String.valueOf(position));
fragmentClass = MybookingFragment.class;
case 2:
Log.d("position1", String.valueOf(position));
fragmentClass = TrackingFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.mainContent, fragment).commit();
}
答案 0 :(得分:5)
因为你永远不会破坏你的开关案例
switch (position) {
case 0:
Log.d("position1", String.valueOf(position));
fragmentClass = FarecardFragment.class;
break;
case 1:
Log.d("position1", String.valueOf(position));
fragmentClass = MybookingFragment.class;
break;
case 2:
Log.d("position1", String.valueOf(position));
fragmentClass = TrackingFragment.class;
break;
}
break语句是必要的,因为没有它们,匹配的case标签之后的所有语句都会按顺序执行,而不管它们的case标签,直到遇到break语句或case结束。