【问题标题】:FragmentManager.findFragmentByTag always returns nullFragmentManager.findFragmentByTag 始终返回 null
【发布时间】:2015-09-13 16:59:30
【问题描述】:

我有一个Activity,在其中我通过替换Fragment 来切换内容。 在这个ActivityonCreate中,我用这个代码设置了第一个Fragment

fm.beginTransaction().add(R.id.container, new FooFragment(), "f_0").commit();

之后,我想根据Integer(我使用抽屉)将这个Fragment换成另一个Fragment,代码如下:

int position = //I get my index here
Fragment f = fm.findFragmentByTag("f_" + position); //(1)

if (f == null) {
    switch (position) {
        case 0:
            f = new FooFragment();
            break;
        case 1:
            f = new BarFragment();
            break;
        //Etc...
    }
}

//Then I replace the actual Fragment by the new one
fm.beginTransaction()
    .replace(R.id.container, f, "f_" + position)
    .commit();

我的问题是 (1) 上的代码总是返回 null,所以每次我更改 Fragment 时,它都会创建一个新实例。我希望每个Fragment 类型在任何时候都只有一个实例。

谢谢。

【问题讨论】:

    标签: android android-fragments fragmentmanager


    【解决方案1】:

    设置第一个片段:

    getSupportFragmentManager().beginTransaction().addToBackStack("f_0").replace(R.id.container, new FooFragment(), "CURRENT_FRAGMENT_TAG").commit();
    


    使用此函数替换片段:

    public void replaceFragment(Fragment fragment, String tag) {
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag("CURRENT_FRAGMENT_TAG");
    
        //to avoid adding the same fragment, you can use 'instanceof' instead of comparator
        if (currentFragment.getClass() == fragment.getClass()) {
            return;
        }
        getSupportFragmentManager().popBackStack(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        getSupportFragmentManager()
                .beginTransaction()
                .addToBackStack(tag).replace(R.id.container, fragment, "CURRENT_FRAGMENT_TAG")
                .commit();
    
    }
    

    示例执行:

    replaceFragment(new FooFragment(), "f_" + position);
    


    覆盖onBackPressed

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
            finish();
        } else {
            super.onBackPressed();
        }
    }
    

    【讨论】:

    • 遇到了同样的问题:/ 我用static int 进行了测试,以计算FooFragment 的实例数,它仍然每Fragmentswap 增加一次。
    • 所以如果你真的想要一个片段实例(onCreate 只会被调用一次),那么你不应该使用 mu 解决方案,并且在你的片段中,在 onCreate 方法中添加 @ 987654331@.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2015-08-15
    • 2012-03-18
    • 2016-11-04
    • 2016-07-28
    • 2010-11-08
    • 2017-11-26
    相关资源
    最近更新 更多