Home > Net >  Spinner not showing options in kotlin fragment
Spinner not showing options in kotlin fragment

Time:06-07

I'm trying to add options to spinner while using databinding in fragment but it's not working, I can't understand why

class AddTransaction: Fragment() {
private var _binding: TransactionAddFragmentBinding? = null
private val binding get() = _binding!!

lateinit var spinner: Spinner

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = TransactionAddFragmentBinding.inflate(inflater, container, false)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
}

fun spinner() {
    spinner = binding.spinnerCategory
    spinner.adapter = ArrayAdapter.createFromResource(
        requireContext(), R.array.categories, R.layout.transaction_add_fragment)
}

}

CodePudding user response:

Based on what you have posted, you are most likely never calling your spinner() function, which means you never set the adapter so it remains empty.

You were also passing R.layout.transaction_add_fragment to the spinner adapter, which is probably not what you wanted. The layout resource you pass in there should be for the spinner row.

Instead of putting it in a separate function, just add it to onViewCreated, like this:

class AddTransaction: Fragment() {
    private var _binding: TransactionAddFragmentBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = TransactionAddFragmentBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // set the adapter here, and there is no need to make a separate "spinner"
        // class member since "binding" is already a class member that contains
        // the spinner
        binding.spinnerCategory.adapter = ArrayAdapter.createFromResource(
            requireContext(), R.array.categories, android.R.layout.simple_spinner_item)
    }
}
  • Related