如何在触摸时立即改变矩形的颜色?

How to change color of Rects instantly when touched?

我正在开发一个使用 ml kit 文本识别库的应用程序;该应用程序从图像中读取文本并在每个单词周围放置一个 Rect。 现在我希望这些 Rects 在用户点击其中一个或在某些单词上方滑动时改变颜色。 所以,我能够正确处理触摸事件,但是 我不能做的是改变触摸的颜色 Rect!

我应该在触摸的矩形上方绘制新的彩色矩形吗?或者我可以为现有的矩形着色(我认为我不能)?

类: TextGraphic, GraphicOverlay//这是绘制矩形的地方

我也试过this solution,所以我在TextGraphicclass中输入了这个方法:

public void changeColor(boolean isHighlighted) {
    if(isHighlighted) {
        rectPaint.setColor(COLOR_HIGHLIGHTED);
        rectPaint.setAlpha(400);//set opacity of rect
    }else{
        rectPaint.setColor(COLOR_DEFAULT);
        rectPaint.setAlpha(400);//set opacity of rect
    }
    postInvalidate();
}

并在用户触摸文本时调用它,但问题是所有 Rects 颜色都会改变,而且它们在运行时不会改变!

我的 ActivityClass 的一个片段,我在其中使用了一些回调方法来传递东西。

ArrayList<Rect> rects = new ArrayList<>();

@Override
public void onAdd(FirebaseVisionText.Element element, Rect elementRect, String wordText) {
   GraphicOverlay.Graphic textGraphic = new TextGraphic(mGraphicOverlay, element);
   mTextGraphic = new TextGraphic(mGraphicOverlay, element);
   mGraphicOverlay.add(textGraphic);


   rects.add(elementRect);
}

我处理触摸事件的 ActivityClass 的片段:

@Override
public boolean onDown(MotionEvent event) {
   helper.dismissKeyboard();
   touchX = Math.round(event.getX());
   touchY = Math.round(event.getY());
   for(int x=0; x< rects.size();x++) {
       if (rects.get(x).contains(touchX, touchY)) {
           // line has been clicked
           mTextGraphic.changeColor(true);

           return true;
       }
   }
   return true;
}

也许你不应该通过编码来完成,而应该通过 ColorStateList 来完成 Android Developer: colorstatelist

您正在使用 mTextGraphic 变量更改颜色。如果您仔细查看 onAdd() 方法,您会发现您正在将一个新对象分配给 mTextGraphic,这与绘制到屏幕上的对象无关,因为只有您添加到 [=15 的对象=] 使用 mGraphicOverlay.add() 的列表将被绘制到屏幕上。

所以你需要的是调用 changeColor() 而不是 mTextGraphic 而是已经在 GraphicOverlay

列表中的相应对象

由于 GraphicOverlay 中的列表是私有的,因此您无法在 onDown() 方法中对其进行操作。您需要编写一个 public 方法来完成这项工作。

GraphicOverlayclass

中写入如下方法
public TextGraphic getGraphicElementAtIndex(int index) {
    return (TextGraphic)graphics.get(index)
}

现在在 onDown() 方法的 if 条件中使用这个方法,像这样

if (rects.get(x).contains(touchX, touchY)) {
    // line has been clicked
    Log.d("PreviewActivity", "changeColor() is called");
    mGraphicOverlay.getGraphicElementAtIndex(x).changeColor();
    touchedText = texts.get(x);
    return true;
}

希望对您有所帮助。

旁注: 现在即使在这之后如果出于某种原因 rects 列表和 graphics 列表中的对象排序(在 GraphicOverlay) 里面改变然后你会看到当你点击一个矩形时一些其他的矩形改变颜色。