findFragmentByTag returning null in android

时间:2016-04-04 18:55:42

标签: android android-fragments

I want to call a fragment method from its parent activity. For that i want object of fragment.

parent activity have fragment in framelayout like this:

<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"

This is the code for getting fragment object.

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");
        }

But it is returning null.

can anyone help me on this? what is wrong here?

2 个答案:

答案 0 :(得分:5)

When you using commit() method nobody gives to you guarantee that your fragment will be attached to FragmentManager on the fly.

This happens due to inner FragmentManager logic : when you add\replace\remove any fragments you create a FragmentTransaction and puts it into execution queue inside FragmentManager. Actually all Transactions waiting until FragmentManager enqueue tasks.

To avoid this situation you can force enqueue each task under Fragment via

getSupportFragmentManager().executePendingTranscation();

This method starts pending Transactions and make more hard sure for use findFragmentById() method.

So, finally you need :

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

getSupportFragmentManager().executePendingTranscation();

CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("FragmentTag");

答案 1 :(得分:0)

Your Fragment is not attached yet. You need to call findFragmentByTag() later on. You can for exemple add a listener to you Fragment and call your Activity on the onAttach() method to tell your Activity that your Fragment is created.