android-fragments 微调器未显示Kotlin片段中的选项

bsxbgnwa  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(162)

我尝试在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)
}

}

fkvaft9z

fkvaft9z1#

根据您发布的内容,您很可能从未调用过spinner()函数,这意味着您从未设置适配器使其保持为空。
您还将R.layout.transaction_add_fragment传递给微调适配器,这可能不是您想要的。您传递到那里的布局资源应该是微调行的。
不要把它放在一个单独的函数中,只需把它添加到onViewCreated中,如下所示:

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)
    }
}

相关问题