拖动/保持/输入另一个TextView边界?

时间:2016-04-12 16:29:17

标签: android

我有一些TextView,并希望在ACTION_DOWN发生后,当手指移动/击中/进入其边界时,它们的背景变为红色。

我尝试使用触摸式监听器,但它不起作用,因为在单击(仅触发ACTION_DOWN)其中一个TextView并将其拖动后,TextView的其余部分不会变为红色(仅第一个,ACTION_DOWN发生的地方变成红色背景)。我将所有TextView附加到OnTouch侦听器并尝试了ACTION_MOVE,但仍然没有结果。

任何人都可以提供帮助?感谢。

类似于此问题Touch (not click) listener

public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE:
            if (selectMode == 0) {
                v.setBackgroundColor(Color.WHITE);
            }else{
                v.setBackgroundColor(Color.RED);
            }
            return true;
        case MotionEvent.ACTION_DOWN:
            if (selectMode == 0) {
                selectMode = 1;
            }else{
                selectMode = 0;
            }
            return true;
    }
    return true;
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

Rect outRect = new Rect();
int[] location = new int[2];

// Attach all of the TextView to the onTouch listener
public boolean onTouch(View v, MotionEvent event) {
    // get the event x and y coordinate
    int x = (int) event.getRawX();
    int y = (int) event.getRawY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE:
            // My viewArray is list of TextView that I want to check that the "touch" hit/enter the TextView area
            for (int i = 0; i < viewArray.length; i++) {
                // Get the area of TextView
                viewArray[i].getDrawingRect(outRect);
                // Get the location of TextView 
                viewArray[i].getLocationOnScreen(location);
                // Move the outRect to the TextView location
                outRect.offset(location[0], location[1]);
                // Check if the "touch" collide with the TextView area (outRect)
                if (outRect.contains(x, y)){
                    if (selectMode == 0) {
                        viewArray[i].setBackgroundColor(Color.WHITE);
                    } else {
                        viewArray[i].setBackgroundColor(Color.RED);
                    }
                }
            }
            return true;
        case MotionEvent.ACTION_DOWN:
            if (selectMode == 0) {
                selectMode = 1;
            }else{
                selectMode = 0;
            }
            return true;
    }
    return true;
}