前言:公司的一个产品需求,需要将列表的最后可见的一项做透明度以及缩放处理,并且在滑动时,最后可见的一项可以淡入淡出的显示在列表中。效果如图~

实现:
调研:起初的设计方案是使用开源项目:RecyclerView Animators https://github.com/wasabeef/recyclerview-animators
但是过不了UI那关,于是便只能想办法实现滑动监听时,做一系列的效果了~
设计分析:
已经确定了要实现RecyclerView滑动监听,必然就得了解RecyclerView滑动监听实现的方法:
1.onScrollStateChanged //滑动状态的改变
2.onScrolled //滑动时回调该方法
这里不需要第一个方法,因此我们就重写onScrolled方法:
1.找到列表中最后一项可见的view
2.根据可见部分占view总部分的占比,计算出透明度以及缩放比例。
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| private void calculateAlphaAndScale(RecyclerView recyclerView, LinearLayoutManager layoutManager) { //找出列表中可见的最后一项索引。 int firstItemPosition = layoutManager.findFirstVisibleItemPosition(); int lastItemPosition = layoutManager.findLastVisibleItemPosition(); //根据索引找到view View lastView = layoutManager.getChildAt(lastItemPosition - firstItemPosition); if (lastView != null) { //当找到最后一项的view时,根据可见部分占view总部分的占比,计算出透明度以及缩放比例。 int itemHeight = lastView.getHeight(); int visibleHeight = recyclerView.getHeight() - lastView.getTop(); if (visibleHeight < 0) { return; } float ratio = visibleHeight * 1.0f / itemHeight; if (ratio > 1.0) { return; } lastView.setAlpha(ratio); float scale = 0.8f;//默认最小的缩放比例 float scaleFactor = scale + (1 - scale) * ratio; lastView.setScaleX(scaleFactor); lastView.setScaleY(scaleFactor); } }
|
最重要的动画部分已经实现,但是还存在一些问题,实际项目中的还有tab切换,导致的列表刷新(由于时间紧迫,并没有采取ViewPager+Indicator的方式)时,已经做缩放和透明度的View没有还原。因此:
在每次做动效前,先遍历列表view,初始化一下状态。
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); int childCount = layoutManager.getChildCount(); //对每个item进行初始化 for (int i = 0; i < childCount; i++) { layoutManager.getChildAt(i).setAlpha(1); layoutManager.getChildAt(i).setScaleY(1); layoutManager.getChildAt(i).setScaleX(1); } calculateAlphaAndScale(recyclerView, layoutManager); }
|
这样,全部的动效就已经完毕了,跑在手机上的效果就如前面的gif图~
作者 :
Lian Yuchen(ShadowHappiness)
著作权归作者所有,转载请联系作者获得授权。