質問

I have created a custom View in Android and depending on the Users wish it will show a different amount of Rectangles for Example 3x3.

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int counter = -1;
    for (int w = 0; w < Rectangles; w++) {
        for (int h = 0; h < Rectangles; h++) {
            Rect rect = new Rect(screen * h + rowDiv, screen * w + rowDiv + topPadding,
                    screen * (h + 1) - rowDiv, screen * (w + 1) - rowDiv + topPadding);
            rectList.add(rect);
            canvas.drawRect(rect, paint);
        }
    }
}

Well this works fine and in the OnTouchListener I want to give Feedback to the User if he presses a Rectangle. Currently the Rectangle disappears if the User clicks it, but it's supposed to change the Color.

@Override
public boolean onTouchEvent(MotionEvent event) {
    int touchX = (int) event.getX();
    int touchY = (int) event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE:
        break;
    case MotionEvent.ACTION_DOWN:
        for (int c = 0; c < rectList.size(); c++) {
            if (rectList.get(c).contains(touchX, touchY)) {
                selectedRect = rectList.get(c);
                selectedRectInt = c;
            }
        }
        break;
    case MotionEvent.ACTION_UP:
        if (selectedRect != null && selectedRectInt != -1)
        if (selectedRect.contains(touchX, touchY) && rectListener != null){
            rectListener.onClick(selectedRectInt);
            invalidate(selectedRect);
        }
        selectedRect = null;
        selectedRectInt = -1;
        break;
    }
    return true;
}

What is the best practise to acomplish this? Do I have to rerun the whole onDraw process by calling invalidate()?

役に立ちましたか?

解決

To simply answer your question: yes, you do need to rerun the onDraw process with invalidate().

Here's how I'd do it:

  1. Create an ArrayList of Paints. You'll need to be able to assign one to each rectangle so you can draw the rectangles with the correct color. Add however many default paint colors you might need. So if the user can only create up to 9 rectangles, add 9 Paints of the same initial color:

    for (int i = 0; i < MAX_RECTS; i++) {
        paintListName.add(new Paint());
        paintListName.get(i).setColor(Color.BLACK); //Your default color
    }
    
  2. Then, in the onTouchEvent method, change the color of the paint that is to be associated with the selected rectangle, then redraw:

    for (int c = 0; c < rectList.size(); c++) {
        if (rectList.get(c).contains(touchX, touchY)) {
            //Set it to color of your choice
            paintListName.get(c).setColor(Color.GREEN);
            invalidate();
        }
    }
    
  3. In onDraw, you should create each rectangle with its associated color:

    canvas.drawRect(rect, paintListName.get(c));
    
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top