I want to make sure that in a recycler view (horizontal orientation and LinearLayoutManager
set) that if I have 2 items to display they both get 50% of the parent layout. So both fit in the screen.
I have tried 2 approaches but neither works properly.
Approach 1:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.horizontal_list_item_view, parent, false)
itemView.post(
object : Runnable {
override fun run() {
itemView.layoutParams.width = (parent.width * 0.5).toInt()
}
}
)
return ViewHolder(itemView)
}
This does not work unless I first scroll and then only the first item has its width adapted.
Approach 2:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.horizontal_list_item_view, parent, false)
itemView.layoutParams.width = getScreenWidthFromUtils(context).x_width - MAGIC_NUMBER_WHICH_TAKES_PADDING_INTO_ACCOUNT)* 0.5).toInt()
return ViewHolder(itemView)
}
Approach 2 kind of works but obviously it can't be the solution as I doubt it has to be this complicated to achieve this.
What is the proper way to do this?