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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With