0

I have an extension function with FragmentManager as receiver. I have used it at atleast 75 places. Now I want to access sharedpreference in that extension. All I need is context inside that function. Any way I can access context?

Here is how function looks,

inline fun FragmentManager?.loadFragment(...){
 ....
 // Loading of fragment
 // inside I want context
}
Aziz
  • 1,976
  • 20
  • 23
  • 1
    Overload method `loadFragment` with context as parameter .. – ADM Dec 19 '19 at 07:27
  • I thought so and I did with optional params but I simply cannot because it is used in several places which is why I asked. – Aziz Dec 19 '19 at 07:29
  • You can not get Context from a `FragmentManager` so i think this is what you should do .. There could be cases where you do not need Context So you can utilize both variants. – ADM Dec 19 '19 at 07:32

2 Answers2

0

You can get context from FragmentManager, but I would not advise it.

 inline fun FragmentManager?.loadFragment() {
    // Get the context of the last fragment added to the fragment manager
    val context = this?.fragments?.last()?.context

 }
Thomas Cook
  • 4,371
  • 2
  • 25
  • 42
  • Thats exactly how I did it, the only difference is I used `findFragmentById`, my need of context was after the second fragment. So this solved my problem. Thanks for your help – Aziz Dec 24 '19 at 13:00
0

The above answer is returning null context as it is not advisable to use by @Thomas. So I referred to this.

Aziz
  • 1,976
  • 20
  • 23