findFragmentByTag在android中返回null

Dev*_*wal 1 android android-fragments

我想从其父活动中调用片段方法.为此,我想要片段的对象.

父活动在framelayout中有片段,如下所示:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/bottom_buttons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
Run Code Online (Sandbox Code Playgroud)

这是获取片段对象的代码.

FragmentBottomButtons fragment = new FragmentBottomButtons();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.bottom_buttons, fragment,"FragmentTag");
        //ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        //ft.addToBackStack("");
        ft.commit();


        /*
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.bottom_buttons, new FragmentBottomButtons())
                .commit();

        */
        frag = (FragmentBottomButtons) getSupportFragmentManager().findFragmentByTag("FragmentTag");
        //fragmentBottomButtons = (FrameLayout)findViewById(R.id.bottom_buttons);
        if (frag == null){
            Utility.displayToast("fragmnt is null");
        }
Run Code Online (Sandbox Code Playgroud)

但它返回null.

谁可以帮我这个事?这有什么不对?

Ser*_*kov 5

当您使用commit()nobody给出的方法保证您的片段将动态附加到FragmentManager.

这是由内部FragmentManager逻辑引起的:当您添加\ replace\remove时,您创建一个片段FragmentTransaction并将其放入FragmentManager内的执行队列中.实际上所有事务都在等待FragmentManager排队任务.

为避免这种情况,您可以强制将每个任务排入Fragment via下

getSupportFragmentManager().executePendingTranscation();
Run Code Online (Sandbox Code Playgroud)

此方法启动待处理的事务,并使用findFragmentById()方法更加确定.

所以,最后你需要:

CustomFragment fragment = new CustomFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//add or replace or remove fragment
ft.commit();

getSupportFragmentManager().executePendingTranscation();

CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("FragmentTag");
Run Code Online (Sandbox Code Playgroud)