Michael Ray Lovett Michael Ray Lovett - 4 months ago 38x
Android Question

android how and when to use getSupportFragmentManager (newbie is confused)

I'm just getting started with Android development and am trying to follow an example in a book and it's not compiling.

The book has me creating a Fragment in my application and then interacting with that fragment in my MainActivity; specifically the book says to call getFragmentManager().findFragmentByID(..) in the main activity, in order to access this fragment, but this is returning an error that the results of getFragmentManager can't be converted to the right type.

So I started poking around and noticed that by default, my installation of Android Studio is apparently using the v4 support library and so my Fragments are v4 Fragments and not the standard sdk Fragments (please correct me if I'm misinterpreting the situation).. and because of this, the call to getFragmentManager is apparently not the right way to get at a v4 Fragment.

Apparently I'm supposed to be calling getSupportFragmentManger instead, but Android Studio says that's not defined. I tried guessing what kind of import I might need in my main activity for it to be able to see getSupportFragmentManager, but I can't seem to figure that out either.

Any help at straightening this out would be very much appreciated.

I have looked at the v4 docs on google's site but honestly to a newbie it's not clear what calls go with what.



If you want to use support classes in your Activity, then it should also be an Activity from support library.

To accomplish that your Activity must extend AppCompatActivity.

public class MainActivity extends AppCompatActivity {

    //Your code that calls getSupportFragmentManager()