【问题标题】:How to Highlight the Competely visible item view in a RecyclerView如何在 RecyclerView 中突出显示竞争可见的项目视图
【发布时间】:2020-10-01 22:20:44
【问题描述】:

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

}

【问题讨论】:

    标签: java android android-recyclerview android-adapter


    【解决方案1】:

    当你用这个找到中心点时

    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
    }
    

    我希望这会奏效。

    【讨论】:

    • 这仅在您向下滚动时有效。但是当您向上滚动时,所有 cardViews alpha 都是 1f。当您向上和向下滚动时,我上面的代码有效。唯一的问题是当我到达位置 4(中心视图)向下滚动时,它的 alpha 变为 1f,这很好,但随后立即变回 .5f。
    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 2021-08-31
    • 2023-03-25
    • 1970-01-01
    • 2012-05-09
    • 2014-12-21
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多