我尝试在fragment中使用数据绑定时向Spinner添加选项,但它不起作用,我不明白为什么
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)
}
}
1条答案
按热度按时间fkvaft9z1#
根据您发布的内容,您很可能从未调用过
spinner()
函数,这意味着您从未设置适配器使其保持为空。您还将
R.layout.transaction_add_fragment
传递给微调适配器,这可能不是您想要的。您传递到那里的布局资源应该是微调行的。不要把它放在一个单独的函数中,只需把它添加到
onViewCreated
中,如下所示: