Spinner position 0 not called in Fragment

Viewed 29

I'm creating an app using Spinner in one Fragment.

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val t=inflater.inflate(R.layout.fragment_add, container, false)
    val spinner = t.findViewById<Spinner>(R.id.spinner)
    spinner?.adapter = ArrayAdapter(activity?.applicationContext, R.layout.support_simple_spinner_dropdown_item, types) as SpinnerAdapter
    spinner?.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            if(view!=null){
                val type = parent?.getItemAtPosition(position).toString()
                Toast.makeText(activity,type, Toast.LENGTH_LONG).show()
                println(type)
            }

        }

    }
    return t
}

Everything works fine for the first time I loaded. But when I go to another Fragment using Tablayout and come back to that Fragment, the first position not get called. Although if I set the spinner position to 1 or 2 and go to another and come back, position 1 gets called.

I mean the problem only occurs if I set position to 0 and go to another Fragment and come back. (The view get null)

How to fix this, please?

0 Answers
Related