Getting 0 Value for both X and Y Coordinate of view(Imagebutton) in android

前端 未结 4 1414
失恋的感觉
失恋的感觉 2021-01-01 05:46

I want to get X and Y Point of View(ImageButton).

When I try to find X and Y on Click event with below code I get proper X and Y coordinate for View.



        
4条回答
  •  -上瘾入骨i
    2021-01-01 06:32

    the reason the returned value is zero is because the ImageButton is not yet created if you call this method in 'onCreate()'. You can use the ViewTreeObserver to get the position:

    ViewTreeObserver vto = imagebutton.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            this.imagebutton.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
    
            int[] posXY = new int[2];
    
            imagebutton.getLocationOnScreen(posXY);
            x = posXY[0];
            y = posXY[1];
    
            Log.d("X and Y Point", x + " " + y);  
    
        } 
    });
    

    Happy coding

提交回复
热议问题