Scaling a RecyclerView Object Based on Its Position

I am trying to achieve a RecyclerView as shown below:

enter image description here

Elements are views of the same type, but with different scales. I tried to call

view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); 

In the OnBindViewHolder adapter method, as well as in ItemDecorator, but each time the behavior of the list was unexpected. What is the best approach to achieving it? It may be with some other control, like a PagerAdapter or another.

UPD: the scaling factor depends on the position of the element in the adapter and should not change when scrolling.

UPD2: Here is the code I tried in OnBoundViewHolder:

 int childCount = recyclerView.getChildCount(); View view = holder.getView(); if (position == childCount){ view.setScaleX(1f); view.setScaleY(1f); } else if (position == childCount - 1){ view.setScaleX(0.8f); view.setScaleY(0.8f); } else if (position == childCount - 2){ view.setScaleX(0.6f); view.setScaleY(0.6f); } else { view.setScaleX(0.4f); view.setScaleY(0.4f); } 

And here is the result (and it changes when scrolling):

enter image description here

And the same code, but in ItemDecorator getItemOffsets :

enter image description here

+5
source share
1 answer

The problem is that you base the scale according to the position regarding the number of children inside the RecyclerView

Remember that in the recycler view there will never be more children than is currently visible (+ additional delta). This is NOT an indicator of how many items your reseller will display. For example, a processor with 1000 items will only have a number of children of about 6-7, depending on the size of each item in the list.

What you want to do is compare the position with the number of elements

A fix is ​​suggested here:

 int totalItems = getItemCount(); View view = holder.getView(); if (position == totalItems - 1){ // final position will equal total items - 1 view.setScaleX(1f); view.setScaleY(1f); } else if (position == totalItems - 2){ view.setScaleX(0.8f); view.setScaleY(0.8f); } else if (position == totalItems - 3){ view.setScaleX(0.6f); view.setScaleY(0.6f); } else { view.setScaleX(0.4f); view.setScaleY(0.4f); } 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1246924/


All Articles