Search code examples
androidfragmentonactivityresult

Get Current Visible Fragment From Activity


In my (now deprecated) ActionBarActivity, I want to find out what Fragment is visible so I can call a method inside the correct one.

I am doing it like this but it says I cannot cast Fragment with any of the 3 Custom Fragments I created:

if (requestCode == 99) {
    Fragment f = getFragmentManager().findFragmentById(R.id.main_frag);
    if (f instanceof GasFragment) {
        // call method
    } else if (f instanceof OilFragment) {
        // call method
    } else if (f instanceof VehicleFragment) {
        // call method 
    }
}

I have added a tag name for each Fragment so I was also researching a "find fragment by tag" and have not found anything on that front either.

Basically the code above is inside onActivityResult. I catch a result and then do the above block of code.


NOTE: The above code was my second method to accomplishing the same thing But I have gotten neither option to work. Originally, I opened a SettingsActivity inside my Nav Drawer and used a startActivityFromResult(). I wanted the result to be caught inside the open Fragment to call the relevant method. However, I was unable to catch the result from the Fragment's onActivityResult() so I decided to do the above code block in the parent's ActionBarActivity onActivityResult() instead.

If this plan is a more efficient idea, I'd accept that answer as well.


Solution

  • I suppose all your Fragments are extending from android.support.v4.app.Fragment?

    In this case, you have to use getSupportFragmentManager().findFragmentById(), as getFragmentManager().findFragmentById() will return a android.app.Fragment