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

最佳答案

您可以询问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
    });

关于android - 如何避免重复 fragment ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25379732/

10-12 04:18