我的片段(fragment_x)中有一个按钮,下面是OnClickListener
:
private void onClickAddButton(View view){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment_y fragment_y = new Fragment_y();
fragmentTransaction.add(R.id.rl_activity_main_container, fragment_x);
fragmentTransaction.commit();
}
问题是此按钮始终可见,因此再次单击该按钮将再添加一个fragment_y并且屏幕变得混乱。如何检查fragment_y是否已添加,以便我可以避免创建重复的fragment_y?
答案 0 :(得分:6)
您可以询问FragmentManager
是否已添加片段:
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null) {
// fragment must be added
fragment = new Fragment();
fm.beginTransaction().add(R.id.container, fragment, tag);
} else {
// fragment already added
});