3

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?

Jim
  • 3,845
  • 3
  • 22
  • 47
  • Does this answer your question? [Android percent screen width in RecyclerView item](https://stackoverflow.com/questions/51201482/android-percent-screen-width-in-recyclerview-item) – Pawel Apr 28 '20 at 15:09
  • 1
    Why don't you use a `GridLayoutManager` instead of a `LinearLayoutManager` ? – Biscuit Apr 28 '20 at 16:49
  • @Biscuit: How would that help? I can switch if that solves it – Jim Apr 29 '20 at 07:47

1 Answers1

1

The GridLayoutManager will take care of giving your item the optimal size and space for the number of column you specify. In your case you want to have 2 items per row so your code should look like :

val gridLayoutManager = GridLayoutManager(context, 2, GridLayoutManager.HORIZONTAL, false)
Biscuit
  • 4,840
  • 4
  • 26
  • 54
  • I'm using it horizontally as well. ```recyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2, GridLayoutManager.HORIZONTAL, false));``` but it gives me two rows instead of one. Any idea why? – DIRTY DAVE Jun 07 '22 at 11:38
  • You should look at what are GridLayoutManager and LinearLayoutManager – Biscuit Jun 07 '22 at 12:17