Issue
I am trying to change first text(position = 0) gravity from List in 'onBindViewHolder(viewHolder: ViewHolder, position: Int)', but, except for the first, the gravity of some elements changes. Could you tell me where this problem comes from?
You can see code below and also logs
class ButtonsListAdapter(private val dataSet: List<String>) :
RecyclerView.Adapter<ButtonsListAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView
val divider: View
init {
textView = view.findViewById(R.id.textView)
divider = view.findViewById(R.id.divider)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.buttons_list_item, viewGroup, false)
return ViewHolder(view)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.textView.text = dataSet[position]
if(position == 0) {
Log.i("Position", " position -> $position ")
viewHolder.textView.gravity = Gravity.START or Gravity.CENTER_VERTICAL
}
Log.i("Position", " gravity -> $position " + viewHolder.textView.gravity)
}
override fun getItemCount() = dataSet.size
}
Logs
I/Position: position -> 0
I/Position: gravity -> 0 8388627
I/Position: gravity -> 1 17
I/Position: gravity -> 2 17
I/Position: gravity -> 3 17
I/Position: gravity -> 4 17
I/Position: gravity -> 5 17
I/Position: gravity -> 6 17
I/Position: gravity -> 7 17
I/Position: gravity -> 8 17
I/Position: gravity -> 9 8388627
I/Position: gravity -> 10 17
I/Position: gravity -> 11 17
I/Position: gravity -> 12 17
I/Position: gravity -> 13 17
I/Position: gravity -> 14 17
I/Position: gravity -> 15 17
I/Position: gravity -> 16 17
I/Position: gravity -> 17 17
I/Position: gravity -> 9 8388627
I/Position: gravity -> 8 17
I/Position: gravity -> 7 17
I/Position: gravity -> 6 17
I/Position: gravity -> 5 17
I/Position: gravity -> 4 17
I/Position: gravity -> 3 17
I/Position: gravity -> 2 17
I/Position: gravity -> 1 17
I/Position: position -> 0
I/Position: gravity -> 0 8388627
Solution
I believe the RecyclerView tries to use old rows to save on memory usage. It's kinda like: when the view 0 goes out the screen, the new line 9 will "recycle" it to show itself (that why it's called RecyclerView).
If you want a different first line, try override the method int getItemViewType(int position)
and specify that the first item is a "different type" from the rest
(or you could just add an else on if(position == 0)
and force the gravity you want, but I think the other option is more elegant)
Answered By - Luiz Fernando de Moura
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.