Home > Mobile >  Kotlin problem with Spinner inside Fragment
Kotlin problem with Spinner inside Fragment

Time:11-23

I have a problem with spinner inside fragment. Spinner is filled with data, but when i select an item i don't see logs, and in spinner it does not select element. When i used nearly the same code as activity it worked (Just changed context to this in adapter)

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_edit_stoper, container, false)
        val tagSpinner = view.findViewById<Spinner>(R.id.editSpinner)
        val items: MutableList<String> = ArrayList("a","b","c")
        tagSpinner.adapter = ArrayAdapter(this.requireActivity(), android.R.layout.simple_spinner_item, items) as SpinnerAdapter
        tagSpinner.onItemSelectedListener = this

        return view
    }
 override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        Log.d(TAG,"OnItemSelected: $type")
    }
    override fun onNothingSelected(parent: AdapterView<*>?) {
        Log.d(TAG,"error")
    }
}

CodePudding user response:

Try moving your implementation from Fragment directly to spinner. remove override from class and instead of

tagSpinner.onItemSelectedListener = this

do

tagSpinner.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(parent: AdapterView<*>?) {
                Log.d(TAG,"error")
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                Log.d(TAG,"OnItemSelected: $type")
            }

        }

CodePudding user response:

The solution is to add requireActivity().applicationContext in the adapter to change the activityFragment to a context:

...
 val items: MutableList<String> = ArrayList("a","b","c")
 tagSpinner.adapter = ArrayAdapter(requireActivity().applicationContext, android.R.layout.simple_spinner_item, items) as SpinnerAdapter
tagSpinner.onItemSelectedListener = this
...
  • Related