Get the current fragment object
In my main.xml
I have
<FrameLayout
android:id="@+id/frameTitle"
android:padding="5dp"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="@drawable/title_bg">
<fragment
android:name="com.fragment.TitleFragment"
android:id="@+id/fragmentTag"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</FrameLayout>
And I'm setting fragment object like this
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new FragmentType1();
fragmentTransaction.replace(R.id.frameTitle, casinodetailFragment, "fragmentTag");
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
It is setting different types of Fragment objects (FragmentType2,FragmentType3,...
) at different time. Now at some point of time I need to identify which object is currently there.
In short I need to do something like this:
Fragment currentFragment = //what is the way to get current fragment object in FrameLayout R.id.frameTitle
I tried the following
TitleFragment titleFragmentById = (TitleFragment) fragmentManager.findFragmentById(R.id.frameTitle);
and
TitleFragment titleFragmentByTag = (TitleFragment) fragmentManager.findFragmentByTag("fragmentTag");
But both the objects (titleFragmentById and titleFragmentByTag ) are null
Did I miss something?
I'm using Compatibility Package, r3
and developing for API level 7
.
findFragmentById()
and findFragmentByTag()
will work if we have set fragment using fragmentTransaction.replace
or fragmentTransaction.add
, but will return null
if we have set the object at xml (like what I have done in my main.xml
). I think I'm missing something in my XML files.
Now at some point of time I need to identify which object is currently there
Call findFragmentById()
on FragmentManager
and determine which fragment is in your R.id.frameTitle
container.
If you are using the androidx
edition of Fragment
— as you should in modern apps — , use getSupportFragmentManager()
on your FragmentActivity
/AppCompatActivity
instead of getFragmentManager()
Try this,
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
this will give u the current fragment, then you may compare it to the fragment class and do your stuffs.
if (currentFragment instanceof NameOfYourFragmentClass) {
Log.v(TAG, "find the current fragment");
}
I think you can use onAttachFragment event may be useful to catch which fragment is active.
@Override
public void onAttachFragment(Fragment fragment) {
// TODO Auto-generated method stub
super.onAttachFragment(fragment);
Toast.makeText(getApplicationContext(), String.valueOf(fragment.getId()), Toast.LENGTH_SHORT).show();
}