Reputation: 66
I have seen guides and tutorials implementing spinner for activities. However the same method doesn't work for fragments. This was my code inside the onCreateView
method of a fragment class
val personnames = arrayOf("akshat" , "mourya")
val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, personnames)
spinner.adapter = arrayAdapter
spinner.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
spinnerText.text = personnames[position]
}
When the ArrayAdapter
method is called on line 2, I get a type mismatch error because the first parameter requires a context and in my code it is a fragment.
I tried doing the same thing in the activity and it worked.
Fragment are supposed to be like mini activities, so why this error propping up?
Also is there any way I can add spinner to my Fragment?
Upvotes: 0
Views: 111
Reputation: 627
Use requireContext() in place of this in line 2.
Like this:
val arrayAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, personnames)
Upvotes: 1
Reputation: 427
Fragment
is not a subclass of Context
so you can't pass this
as the first argument of the ArrayAdapter
constructor.
When you need a Context
object inside a Fragment
you need to use either one of the two functions requireContext()
or requireActivity()
.
Upvotes: 0
Reputation: 599
Try it like this:
val arrayAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, personnames)
Upvotes: 0