如何避免重复的碎片?

时间:2014-08-19 09:16:52

标签: android android-fragments

我的片段(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?

1 个答案:

答案 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
    });