I work on an android app (Kotlin) and I'm trying to make a fragment which contains a spinner - the list of languages. Though I struggle with passing a "context" to an ArrayAdapter.
I tried using "this" and "context". But neither of those worked. Smart casting with "let" doesn't solve the issue and adding "ifs" for null checking doesn't solve the issue either.
How can I access "context" of a fragment? Here I have the code in which I check if the fragment has been added to an activity but the compiler still sees it as "context?" not as "context".
class QuickTranslation : Fragment() {
private lateinit var binding: FragmentQuickTranslationBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = DataBindingUtil.inflate<FragmentQuickTranslationBinding>(
inflater,
R.layout.fragment_quick_translation, container, false
)
if (isAdded) { // HERE I check if contex is null
val originalLangSpinner = binding.originalLangSpinner
ArrayAdapter.createFromResource(
context, // ERROR Type missmatch. Required: Context, Found: Context?
R.array.supported_languages,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
originalLangSpinner.adapter = adapter
}
}
return binding.root
}
}