Pergunta

I would like the touch information relative to the entire screen, but I'm getting touch info just relative to the button.

ButtonTouchListener = new OnTouchListener(){

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
             switch(v.getId()){
                case R.id.somebutton
                          //do things
                    //....etc
            }

           int action = event.getAction();
       switch(action){
       case MotionEvent.ACTION_UP:
         act += event.toString();
         System.out.println("release: " + act);
}};

The x and y I'm getting from the event relates to the button (0, 0 is the corner of the button, not the corner of the screen). How can I get the x and y locations relative to the entire screen ONLY when a button is pressed?

Foi útil?

Solução

To get the touch position relative to the view add the touch event's (x,y) to your button's (x,y); to get the button's position relative to it's parent (your view) use the getLeft() and getTop() methods.

The documentation for View has the following under Position:

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

Example code for your onTouch method:

float screenX = v.getLeft() + event.getX();   // X in Screen Coordinates
float screenY = v.getTop() + event.getY();    // Y in Screen Coordinates

Outras dicas

Best way to do it (as far as I can figure) is to invoke event.getRawX() and event.getRawY(). This works if your view is the whole screen. If not then, I don't know, you're out of luck I guess, but rawx and y work for my purpose.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top