Recycler View has a high degree of freedom, it can be said that only unexpected can not be done, the more the more I like it. This time, in a very simple way, let Recycler View take the folding effect.
The effect is this.
To summarize the characteristics of this list, there are three points:
1. Overlapping effect;
2. Sense of hierarchy;
3. Differential effect of the first item.
Now let's work it out one by one.
We create a new Parallax Recycler View, which inherits Recycler View and uses Linear Layout Manager as layout manager.
Overlapping effect
In fact, each item has a part in front of it. We know that RecyclerView can achieve the spacing effect of lists by setting ItemDecoration. Have you ever wondered what it would be like to set the spacing to a negative number? For example:
addItemDecoration(new ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.bottom = -dp2px(context, 10);
}
});
That's right. That's how we overlap.
Sense of level
In Material Design, there is the concept of Z axis. We can set the height of the control perpendicular to the screen to make the control not at the same height look hierarchical. Of course, we need to use the control of Material Design to have this property. Here I use CardView.
We add a sliding listener to Parallax RecyclerView and set the following settings in the onScrolled method:
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
int firstPosition = layoutManager.findFirstVisibleItemPosition();
int lastPosition = layoutManager.findLastVisibleItemPosition();
int visibleCount = lastPosition - firstPosition;
//Reset the height of the control
int elevation = 1;
for (int i = firstPosition - 1; i <= (firstPosition + visibleCount) + 1; i++) {
View view = layoutManager.findViewByPosition(i);
if (view != null) {
if (view instanceof CardView) {
((CardView) view).setCardElevation(dp2px(context, elevation));
elevation += 5;
}
}
}
The setCardElevation method is used to set the height of CardView, where each item is 5 DP higher than its previous one.
Differentiation of the first item
Finally, we want to add a differential effect to the first item, which is also handled in the onScrolled method.
View firstView = layoutManager.findViewByPosition(firstPosition);
float firstViewTop = firstView.getTop();
firstView.setTranslationY(-firstViewTop / 2.0f);
This is equivalent to half the sliding speed of the first term. However, this can also lead to a problem, because the position of the control is changed, when the control is reused, there will be incorrect location. So when we set the height, we can restore the position of the control by the way:
float translationY = view.getTranslationY();
if (i > firstPosition && translationY != 0) {
view.setTranslationY(0);
}
This completes a Recycler View with a simple folding effect, which is appropriate.