我有以下SpinnerAdapter,它成功地为我提供了一个我的对象Discipline列表,其中包含微调器和下拉项的正确布局样式。但是当我选择其中一个项目时,位置0文本会在所选项目位置上重复。
class ClassesSpinnerAdapter(context: Context, resourceId: Int,
val disciplineClasses: List<Discipline>) : ArrayAdapter<Discipline>(context, resourceId, disciplineClasses) {
override fun getItem(position: Int): Discipline {
return disciplineClasses[position]
}
override fun getCount(): Int {
return disciplineClasses.size
}
override fun getItemId(position: Int): Long {
return super.getItemId(position)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var holder: ClassSpinnerHolder
var rowView: View
if (convertView == null) {
rowView = LayoutInflater.from(parent?.context).inflate(R.layout.classes_spinner_row, parent, false)
holder = ClassSpinnerHolder()
holder.classNameTxt = rowView.findViewById(R.id.classes_spinner_text) as TextView?
holder.classNameTxt?.text = disciplineClasses[position].className.replace("ano", "")
rowView.tag = holder
} else {
holder = convertView.tag as ClassSpinnerHolder
rowView = convertView
}
val discipline: Discipline = disciplineClasses[position];
if (discipline != null) {
holder.classNameTxt?.text = disciplineClasses[position].className.replace("ano", "")
}
return rowView
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
var holder: ClassSpinnerHolder
var rowView: View
if (convertView == null) {
rowView = LayoutInflater.from(parent?.context).inflate(R.layout.classes_spinner_row, parent, false)
holder = ClassSpinnerHolder()
holder.classNameTxt = rowView.findViewById(R.id.classes_spinner_text) as TextView?
holder.classNameTxt?.text = disciplineClasses[position].className.replace("ano", "")
rowView.tag = holder
} else {
holder = convertView.tag as ClassSpinnerHolder
rowView = convertView
}
return rowView
}
inner class ClassSpinnerHolder() {
var classNameTxt: TextView? = null
}
这是我得到的结果:
我有点通过删除getDropDownView()方法并在我的模型类上覆盖toString来解决它,但我想要一个更好的解决方案,我想我以错误的方式覆盖了getDropDownView(),有人可以帮助我吗? / p>
答案 0 :(得分:2)
在getDropDownView()
中,您只更新if (convertView == null)
案例中的观看值。每次调用方法时都应该更新所有值,否则循环视图中会包含垃圾。