如何在RecyclerView中突出显示完全可见的项目视图

问题描述

我在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
}

我希望这会起作用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...