Get the Application Context In Fragment In Android?

后端 未结 8 1442
無奈伤痛
無奈伤痛 2020-12-02 08:36

I have stored some data to a Global Class By using the Application Context In One Activity. Later I have to Retrieve those values in A Fragment. I have done something like t

相关标签:
8条回答
  • 2020-12-02 09:20

    In Support Library 27.1.0 and later, Google has introduced new methods requireContext() and requireActivity() methods.

    Eg:ContextCompat.getColor(requireContext(), R.color.soft_gray)

    More info here

    0 讨论(0)
  • 2020-12-02 09:24

    You can get the context using getActivity().getApplicationContext();

    0 讨论(0)
  • 2020-12-02 09:28

    Pretty late response but you can do the following in Kotlin:

    activity?.applicationContext?.let { SymptomsAdapters(it, param2, param3, ...) }
    

    (?.) is for safe null operation to prevent from the null pointer exception.

    You do not want to create a new context as that can lead to memory leaks when interchanging between fragments or when the device changes rotation.

    And as someone mentioned above, in Java you can obtain context in a fragment by doing the following:

    getActivity().getApplicationContext()
    
    0 讨论(0)
  • 2020-12-02 09:32

    Add this to onCreate

    // Getting application context
            Context context = getActivity();
    
    0 讨论(0)
  • 2020-12-02 09:36

    In Kotlin we can get application context in fragment using this

    requireActivity().application
    
    0 讨论(0)
  • 2020-12-02 09:37

    you can define a global variable :

    private Context globalContext = null;
    

    and in the onCreate method, initialize it :

    globalContext = this.getActivity();
    

    And by that you can use the "globalContext" variable in all your fragment functions/methods.

    Good luck.

    0 讨论(0)
提交回复
热议问题