Using ContextCompat.getColor in fragment Kotlin?

Viewed 1821

I have a check box in fragment and trying to set text color on it using ContextCompat.getColor

the code

optionCb.setTextColor(ContextCompat.getColor(activity,android.R.color.white));

It shows error

required : Context 
Found : fragmentactivity

Even used

optionCb.setTextColor(ContextCompat.getColor(activity.applicationContext,android.R.color.white));

Still shows error

What should be the context object here?

4 Answers

was able to solve by using requireActivity()

optionCb.setTextColor(ContextCompat.getColor(requireActivity(), android.R.color.black));

Try to use requiredActivity or requiredContext instead of activity

The ContextCompat.getColor() accepts two arguments -- the first of which is a non-null Context object.

If you're writing code in Kotlin, Android Studio is likely complaining about the Context object you're passing to getColor() being nullable. The context and activity parameters available to Fragments are nullable in Android.

As others have already mentioned, you can use the requireContext() function. However, while this will satisfy Android Studio, it should be used with caution since it will throw an IllegalStateException if the Fragment's context is null (the context of a Fragment is not always available).

My recommendation would be to set the text color in your xml layout file if at all possible. If you have to do it programmatically, the safest way is to handle the null case:

    context
        ?.let { ContextCompat.getColor(it, android.R.color.white) }
        ?.also { optionsCb.setTextColor(it) }
optionCb.setTextColor(ContextCompat.getColor(getContext(),android.R.color.white));
Related