I use fragments in my application. I needed to redefine the onAttach method inside the fragment onAttach , and it turned out the following: since version 23, this method is called with Context : onAttach(Context) , and before version 23 it is called with Activity : onAttach(Activity) .
That is, it turns out that for different versions of Android you need different code.
How to make the code work equally on different versions of Android?

  • What prevents to override both methods and put identical code in them? - Yuriy SPb
  • @Yuriy SPb so that onAttach (Activity) is marked as deprecated - plesser
  • And the second method will work only for API> 23. This will just have to accept. Mark annotations methods. One as deprecated, the second mark targetApi. The marks will disappear and everything will work - YuriySPb
  • @ YuriySPB - thanks! If you write back, I will gladly tick you as the correct answer. - plesser

2 answers 2

One method is marked as obsolete, and the second method will work only for API> 23. This will just have to accept. Mark annotations methods. One as deprecated, the second mark targetApi. The marks will disappear and everything will work.

  • Perhaps a comment about redefining both methods should also be moved to the answer? - Regent
  • Yes! And thank you very much for the prompt answers! - plesser

Alternatively, you can use the Fragment from the support library. They are updated along with the library itself, and not with the android version. Therefore, all devices will use the version to which you update the support library. In this case, you can use a single method onAttach(Context context) .

Only it will be necessary to replace the standard FragmentManager with the SupportFragmentManager , i.e. call getSupportFragmentManager instead of getFragmentManager . Also activit should be inherited from AppCompatActivity .