K
K
katavagner2015-07-05 22:11:28
Java
katavagner, 2015-07-05 22:11:28

How to determine an element by coordinates?

Using the onTouch function, I determine the element on which the finger was pressed (the cursor in the emulator), then some kind of gesture is made and the finger (the cursor in the emulator) is released over some element.
That is, there are coordinates of the element on which the finger was released, the problem is that I do not know how to get its id or access it.

public boolean onTouch(View v, MotionEvent event) {
        x = event.getX();
        y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: // нажатие
                topY = button1.getTop();
                leftX = button1.getLeft();
                rightX = button1.getRight();
                bottomY = button1.getBottom();

                topY2 = v.getTop();
                leftX2 = v.getLeft();
                rightX2 = v.getRight();
                bottomY2 = v.getBottom();

                tv_elem.setText(
                        topY + "\n" + leftX + "\n" + rightX + "\n" + bottomY  + "\n"  + "\n" +
                        topY2 + "\n" + leftX2 + "\n" + rightX2 + "\n" + bottomY2
                );
                break;
            case MotionEvent.ACTION_MOVE: // движение
                eX = (int) event.getX();
                eY = (int) event.getY();
                int x = (int) event.getX() - offset_x;
                int y = (int) event.getY() - offset_y;
                int w = getWindowManager().getDefaultDisplay().getWidth() - 50;
                int h = getWindowManager().getDefaultDisplay().getHeight() - 10;
                if (x > w) x = w;
                if (y > h) y = h;

                tv_elem.setText(
                        (eX + leftX2) + " " + leftX + " " + rightX + "\n" +
                        (eY + topY2) + " " + topY + " " + bottomY + "\n"
                );

                if ((eX + leftX2) > leftX && (eX + leftX2) < rightX && (eY + topY2) > topY && (eY + topY2) < bottomY) {
                    button1.setBackgroundColor(Color.RED);
                } else {
                    button1.setBackgroundColor(Color.BLUE);
                }

                break;
            case MotionEvent.ACTION_UP: // отпускание
            case MotionEvent.ACTION_CANCEL:
                /* здесь что-то, чтобы проверить над каким элементом отпустили */
                tv_elem.setText("Все, отпустил");
                break;
        }
        return true;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg Gamega, 2015-07-05
@gadfi

you also have a View parameter
v.getId();

B
belozerow, 2015-07-06
@belozerow

Probably just go over all possible views and look at getGlobalVisibleRect through contains.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question