natzelo
natzelo

Reputation: 66

Add and implement a spinner in fragment

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

Answers (3)

Ronak Sethi
Ronak Sethi

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

mhdwajeeh.95
mhdwajeeh.95

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

petrrr33
petrrr33

Reputation: 599

Try it like this:

 val arrayAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, personnames)

Upvotes: 0

Related Questions