0

I am looking at the Fragment documentation from Google Android Fragments

I have been using Fragments created by Android Studio that is non-static For Example:

public class FormsFragment extends Fragment

Why is Google's documentation declaring them as static? What is the reasoning?

public static class DetailsFragment extends Fragment 
Alan
  • 9,331
  • 14
  • 52
  • 97
  • Keyword static at top level class declaration means nothing. http://stackoverflow.com/questions/7486012/static-classes-in-java – Roman Samoilenko Oct 25 '16 at 18:24
  • @RomanSamoylenko so what's the point of declaring them static at the top level? They just feel like messing with us? – Alan Oct 25 '16 at 18:27
  • When I try to declare a top level class `static` I get a compiler warning. So either you found a bug in the documentation or the snippet is really located within another class... – Timothy Truckle Oct 25 '16 at 18:28
  • That is right, top level class cannot be static as well as meaningless – Nayan Srivastava Oct 25 '16 at 18:30

2 Answers2

1

Your question seems that you are classifying fragments by two types . Static and non static, but it is not, there are two types of fragment Static and Dynamic .The keyword static doesn't mean that this is a static fragment . the keyword probably means that that fragment class was a nested inner class , which only can be accessed top level class(probably an activity ).

Mithun Sarker Shuvro
  • 3,902
  • 6
  • 32
  • 64
1

Using fragments you have to follow the contracts given by Android itself. Since the framework manages your activity and fragment lifecycle, it needs to be able to create these classes. This is done with a public default constructor. Also it's required to declare the class itself public.

So if you define the fragment as a "normal" class, you don't have to consider anything else. If you define it as an inner class of another class must declare it static as well. Otherwise the class will have an implicit constructor with a parameter of the type of the outer class and therefore no public default constructor to create a new instance of your fragment.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • could you provide a use case in which you would nest a Fragment? I always use them as the top class. – Alan Oct 25 '16 at 20:40
  • There's no difference in the resulting class. It's just the developers preference to keep it in the same class file as the outer class. – tynn Oct 25 '16 at 20:49