Search code examples
androiddimensions

Android : get location of object for the screen


I trying to get x,y for any object inside the layout but I got this values when object at end corner of the screen :

Object X : 266

Object Y : 361

Screen Width : 320

Screen Height: 480

how can I know where is the object exactly for the screen? (end,top,left,center).


Solution

  • Hope this helps..

    public Rect locateView(View view) {
        Rect loc = new Rect();
        int[] location = new int[2];
        if (view == null) {
            return loc;
        }
        view.getLocationOnScreen(location);
    
        loc.left = location[0];
        loc.top = location[1];
        loc.right = loc.left + view.getWidth();
        loc.bottom = loc.top + view.getHeight();
        return loc;
    }
    

    And I used the method this way:

      Rect r = TVGridUtils.locateView(activity.findViewById(R.id.imageview));                 
    
            float touchX=r.left+((r.right-r.left)/2);
            float touchY=(r.bottom);    
    

    Note: I had to get the middle point of the imageview which i touched