片段内 Spinner 的 Kotlin 问题
Posted
技术标签:
【中文标题】片段内 Spinner 的 Kotlin 问题【英文标题】:Kotlin problem with Spinner inside Fragment 【发布时间】:2021-12-31 23:14:56 【问题描述】:片段内的微调器有问题。微调器充满了数据,但是当我选择一个项目时,我看不到日志,并且在微调器中,它不会选择元素。当我使用几乎与它工作的活动相同的代码时(只是在适配器中将上下文更改为 this)
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")
【问题讨论】:
可能的答案 - ***.com/questions/59401980/… 【参考方案1】:尝试将您的实现从 Fragment 直接移动到 spinner。从类中删除覆盖,而不是
tagSpinner.onItemSelectedListener = this
做
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")
【讨论】:
我已经试过了,还是不行【参考方案2】:解决方法是在适配器中添加requireActivity().applicationContext,将activityFragment改为上下文:
...
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
...
【讨论】:
【参考方案3】:你的片段真的是微调器的监听器吗? 编写一个自定义侦听器并使用它来代替您的片段。
inner class SpinnerStateChangeListener : AdapterView.OnItemSelectedListener
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long)
// do sth here
override fun onNothingSelected(parent: AdapterView<*>?)
// do sth here
现在你可以像这样设置你的监听器:
tagSpinner.onItemSelectedListener = SpinnerStateChangeListener()
【讨论】:
以上是关于片段内 Spinner 的 Kotlin 问题的主要内容,如果未能解决你的问题,请参考以下文章
片段内的 RecyclerView 的 Kotlin OnItemClickListener