问题描述
我在cardView中有一个imageView和一个textView。
cardView的Alpha设置为.5f。
cardView用于垂直的recyclerView。
我要在这里做的是,当用户在reyclerView中滚动时,完全可见的cardView的Alpha值应始终更改为1f,对于不完全可见的cardViews的alpha值应保持为0.5f。
一次只有一个完全可见的cardView。
这是我尝试过的方法,但是不起作用。
@Override
public void onScrolled(RecyclerView recyclerView,int dx,int dy) {
super.onScrolled(recyclerView,dx,dy);
int center = recyclerView.getHeight() / 2;
View centerView = recyclerView.findChildViewUnder( recyclerView.getTop(),center);
int centerPos = recyclerView.getChildAdapterPosition(centerView);
if (prevCenterPos != centerPos) {
// dehighlight the prevIoUsly highlighted view
View prevView =
recyclerView.getLayoutManager().findViewByPosition(prevCenterPos);
if (prevView != null) {
prevView.setAlpha(.5f);
}
// highlight view in the middle
if (centerView != null) {
prevView.setAlpha(1f);
}
prevCenterPos = centerPos;
}
}
解决方法
与此同时您正在寻找中心点
int center = recyclerView.getHeight() / 2;
这不是您应该使用的正确方法:
mLayoutManager.findFirstCompletelyVisibleItemPosition()
尝试一下:
val firstCompelteVisible = mLayoutManager.findFirstCompletelyVisibleItemPosition()
val centerView =
recyclerView.layoutManager!!.findViewByPosition(firstCompelteVisible)
if (prevCenterPos != centerPos) {
// dehighlight the previously highlighted view
val prevView =
recyclerView.layoutManager!!.findViewByPosition(prevCenterPos)
if (prevView != null) {
prevView.alpha = .5f
}
// highlight view in the middle
if (centerView != null) {
prevView!!.alpha = 1f
}
prevCenterPos = centerPos
}
我希望这会起作用。