无法使用Kotlin在BaseAdapter中保持选定的状态

我的代码:

override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View { var view: View? var holder : ProductHolder var product = getItem(p0) if(p1 == null) { var inflator = LayoutInflater.from(context) view = inflator.inflate(R.layout.item_products_list, p2, false) holder = ProductHolder(view) view.tag = holder } else { view = p1 holder = view.tag as ProductHolder } holder.txtName.text = product.name view?.setOnClickListener({ viewT -> product.isSelect = !product.isSelect viewT.isSelected = product.isSelect Log.e("ListProductsAdapter"," View:" + viewT.toString()) }) view?.isSelected = product.isSelect Log.e("ListProductsAdapter", "Name " + product.name + " isSelect: " + product.isSelect.toString() + " View:" + view?.isSelected.toString()) return view!! } 

和selector.xml:

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="false"> <shape android:shape="rectangle"> <solid android:color="@color/default_background"/> <corners android:radius="2dip" /> <stroke android:width="1dp" android:color="@color/selected_button_color"/> </shape> </item> <item android:state_selected="true"> <shape android:shape="rectangle"> <solid android:color="@color/brown_color" /> <corners android:radius="2dip" /> </shape> </item> </selector> 

在向上/向下滚动gridview之后,Log显示view.isSelected = true,但是将视图的背景重置为default(android:state_selected =“false”)。 我如何保持状态选择的观点


我尝试一下:删除setOnClick代码,并设置view?.isSelected = true,但项目的背景仍然没有改变。 为什么?

++++++++++++++++++++++++++++++++++++++++++++++++++经过几个小时的思考,我发现了一种解决方法,但我感到不满意: – 将“ view?.isSelected = product.isSelect ”替换为“ view?.post { holder.view?.isSelected = product.isSelect }

Kotlin language will be the best programming language for Android.