【问题标题】:Highlight item in RecyclerView while Pressed按下时突出显示 RecyclerView 中的项目
【发布时间】:2022-02-07 03:39:48
【问题描述】:

我似乎找不到更简单的方法来仅在按下时突出显示 RecyclerView 项目,但是虽然我提出的这段代码似乎可以正常工作,但如果我向上/向下移动,它将删除突出显示(发生 ACTION_CANCEL)(按下时),但如果我在按下时向右或向左移动,它会保持突出显示(不调用 ACTION_CANCEL 事件)。谁能告诉我为什么或是否有更好的方法?

           itemView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent pEvent) {
                selected_position = getAdapterPosition();
                if(pEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    parent.setBackgroundColor(Color.RED);
                    txtName.setTextColor(Color.GREEN);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_UP) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    int x = (int)pEvent.getRawX();
                    int y = (int)pEvent.getRawY();
                    int[] coordinates = new int[2];
                    parent.getLocationInWindow(coordinates);
                    if(x < (coordinates[0]) || (x > (coordinates[0]) + parent.getWidth())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else if(y < (coordinates[1]) || (y > (coordinates[1]) + parent.getHeight())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else {
                        parent.setBackgroundColor(Color.RED);
                        txtName.setTextColor(Color.GREEN);
                    }
                }
                return false;
            }
        });

【问题讨论】:

  • 基本上这个想法是创建一个蒙版并设置在文本上。看看this对你有没有帮助。
  • 感谢您提供的链接,我不确定它是否描述了我想要实现的目标。我只是想像其他任何时候一样完全突出显示列表行,但在不再选择行时不会保持突出显示(即当我从屏幕上移除手指或将手指移动到不同的行时,我希望它返回默认背景颜色)

标签: android android-recyclerview ontouchlistener


【解决方案1】:

在你的recycler view item.xml的根布局中,你可以写android:foreground="?attr/selectableItemBackground"。当点击发生时,这将突出显示回收站视图项。

例如,假设它是您的回收站视图项目布局:

 <androidx.constraintlayout.widget.ConstraintLayout

    android:id="@+id/item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackground">

     ...

</androidx.constraintlayout.widget.ConstraintLayout>`

【讨论】:

  • 这就是我要找的,谢谢。
  • 如果有帮助,请采纳。
猜你喜欢
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2014-12-21
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多