I am using a custom recyclerview adapter with checkbox so that user can select multiple checked items.
In the beginning I faced duplicate checkbox selection while scrolling down so I added a position array to keep checkbox selection true or false.Now duplicate checkbox selection problem is gone but while scrolling down selected checkbox are deselected.My recyclerview adpater is given below,
class IngredientsAdapter(var context: Context?,var activity: Activity, var ingredientList:ArrayList<String>, var imageID:Int):
RecyclerView.Adapter<IngredientsAdapter.IngredientViewHolder>() {
private var positionArray:ArrayList<Boolean> = ArrayList(ingredientList.size)
private val selectedList=ArrayList<String>()
init {
for (i in ingredientList.indices) {
positionArray.add(false)
}
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): IngredientViewHolder {
val layoutInflater = LayoutInflater.from(p0.context)
return (IngredientsAdapter.IngredientViewHolder(layoutInflater.inflate(R.layout.ingredient_list_row,p0,false)))
}
override fun getItemCount(): Int {
return ingredientList.size
}
override fun onBindViewHolder(p0: IngredientViewHolder, p1: Int) {
p0.imageView.setImageResource(imageID)
p0.textView.text = ingredientList[p1]
p0.checkBox.isChecked = positionArray[p1]
val sharedPreferences= SharedPreferenceHelper(context, SystemConstants.SHARED_PREFS_CHECKDATA)
val checked=sharedPreferences.getPrefsBooleanValue(ingredientList[p1])
p0.checkBox.isChecked = checked
p0.checkBox.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
if(isChecked){
positionArray[p1] = true
selectedList.add(ingredientList[p1])
ingredientList.get(p1)
sharedPreferences.addPrefsBooleanVal(ingredientList[p1],true)
Log.d("debug","selecteditem==>$selectedList")
}else{
positionArray[p1] = false
selectedList.remove(ingredientList[p1])
sharedPreferences.addPrefsBooleanVal(ingredientList[p1],false)
Log.d("debug","selecteditem==>$selectedList")
}
})
}
class IngredientViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var textView= itemView.txt_row!!
var imageView= itemView.image_view!!
var checkBox= itemView.chk_row!!
}
}
Any suggestion is appreciated.