Created
June 27, 2020 13:48
-
-
Save gastsail/33936ac3b30b8435d69ce5ac17eaf5be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AnimalAdapter(private val context: Context) : | |
RecyclerView.Adapter<BaseViewHolder<*>>() { | |
private var animalList = mutableListOf<Animal>() | |
companion object { | |
const val ITEMS_PER_PAGE = 4 | |
} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<*> { | |
val itemWidth: Int = parent.width / ITEMS_PER_PAGE | |
val view = LayoutInflater.from(context).inflate(R.layout.animals_row, parent, false) | |
val layoutParams: ViewGroup.LayoutParams = view.layoutParams | |
layoutParams.width = itemWidth | |
view.layoutParams = layoutParams | |
return AnimalViewHolder(view) | |
} | |
override fun getItemCount(): Int { | |
return if (animalList.size > 0) animalList.size else 0 | |
} | |
fun setAnimals(animalList:MutableList<Animal>){ | |
this.animalList = animalList | |
notifyDataSetChanged() | |
} | |
fun getItem(position: Int): Animal { | |
return animalList[position] | |
} | |
override fun onBindViewHolder(holder: BaseViewHolder<*>, position: Int) { | |
val animalObj = animalList[position] | |
when (holder) { | |
is AnimalViewHolder -> holder.bind(animalObj,position) | |
else -> throw IllegalArgumentException("No viewholder to show this data, did you forgot to add it to the onBindViewHolder?") | |
} | |
} | |
inner class AnimalViewHolder(itemView: View) : BaseViewHolder<Animal>(itemView){ | |
override fun bind(item: Animal,position:Int) { | |
Glide.with(context).load(item.image).centerCrop().placeholder(GlideProgress.setupCircularProgress(context)).into(itemView.animal_image) | |
itemView.animal_name.text = item.name | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment