0

I have a LinearLayout containing a RecyclerView. The RecyclerView's width is set to match_parent so it has the same width as the LinearLayout.

I want to set the width of the data items in the RecyclerView based on the width of the RecyclerView. For example, let's say the RecyclerView has width W and contains 3 data items, and I want to set the width of the first data item to 10dp and the width of the second and third data items to (W-10dp)/2.

How can I achieve this?

1 Answers1

0

get recyclerView width where you have a reference to the RecyclerView (in the Fragment or Activity). Then, send the width value to the adapter:

recyclerWidth = recyclerView.getWidth();
adapter.setWidthOfRecycler(recyclerWidth);

in OnBindViewHolder in the Adapter, change the layout parameters of the ViewHolder to change the width as follow:

@Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position){

                int viewHolderWidth = (recyclerWidth - dpToPx(10))/2;
                if(position == 0){
                    viewHolderWidth = dpToPx(10);
                }
                viewHolder.setLayoutParams(new RecyclerView.LayoutParams(viewHolderWidth ,LayoutParams.WRAP_CONTENT/**height**/));

        }


        public static int dpToPx(float dp) {

                        float resultPix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,context.getResources().getDisplayMetrics());

                        return (int)resultPix;
        }

if the recyclerView.getWidth() method return zero, check this: View's getWidth() and getHeight() returns 0

Islam Assi
  • 991
  • 1
  • 13
  • 18