按屏幕上的确切区域

时间:2012-03-03 21:42:36

标签: java android bitmap

现在是我的代码:

public boolean onTouchEvent(MotionEvent event)
        {
            int action = event.getAction();

            switch(action)
            {
                case MotionEvent.ACTION_DOWN:
                // Do click work here ...
                Y -= 10;
                Yopen = 1;
                break;
                case MotionEvent.ACTION_UP:
                // Do release work here ...
                Yopen = 0;
                break;
                }

            return super.onTouchEvent(event);
    } 

但我想只做三个不同的区域来执行不同的代码。 有人可以帮助我,在互联网上提供一些好的教程。

1 个答案:

答案 0 :(得分:0)

将此代码添加到onTouchEvent中,以确定用户触摸并做出适当响应的位置:

    //Grab the current touch coordinates
    float x = event.getX();
    float y = event.getY();

    //If you only want something to happen then the user touches down...
    if (event.getAction() != MotionEvent.ACTION_UP) return true;

    //If the user pressed in the following area, run it's associated method
    if (isXYInRect(x, y, new Rect(x1, y1, x2, y2)))
    {
        //Do whatever you want for your defined area
    }
    //or, if the user pressed in the following area, run it's associated method
    else if (isXYInRect(x, y, new Rect(x1, y1, x2, y2)))
    {
        //Do whatever you want for your defined area
    }

这是isXYinRect方法:

//A helper method to determine if a coordinate is within a rectangle
private boolean isXYInRect(float x, float y, Rect rect)
{
    //If it is within the bounds...
    if (x > rect.left &&
        x < rect.right &&
        y > rect.top &&
        y < rect.bottom)
    {
        //Then it's a hit
        return true;
    }

    //Otherwise, it's a miss
    return false;
}