在 android 中获取视图(Imagebutton)的 X 和 Y 坐标的 0 值

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

我想要获取 X 和 Y 视角(ImageButton)。

当我尝试使用以下代码在 Click 事件中查找 X 和 Y 时,我得到了视图的正确 X 和 Y 坐标。

    ImageButton imagebutton = findviewbyId(R.id.imagebutton);                       
    imagebutton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            int[] posXY = new int[2];
            v.getLocationOnScreen(posXY);
            x = posXY[0];
            y = posXY[1];

            Log.d("X and Y Point", x + " " + y);        
        }
    });

但是我想要在单击视图之前进行 X 和 Y 坐标,所以我尝试使用以下代码获取 X 和 Y。

    ImageButton imagebutton = findviewbyId(R.id.imagebutton);                       
    int[] posXY = new int[2];
    imageButton.getLocationOnScreen(posXY);
    x = posXY[0];
    y = posXY[1];

    Log.d("X and Y Point", x + " " + y);

但是每当我尝试使用 ClickListener 获取 X 和 Y 时,我得到的 X 和 Y 都是 0 和 0。因此,如果没有 ClickListener,我将无法获得正确的 X 和 Y。 谁能帮助解决实际问题,没有 ClickListener 如何获得正确的 X 和 Y?

两个选项:

  • onResume 中实现您的逻辑。
  • 使用ViewTreeObserver

    final ViewTreeObserver vto = findViewById(R.id.YOUR_VIEW_ID).getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            vto.removeOnGlobalLayoutListener(this);  
    
            // Get X, Y of the ImageView here
        } 
    });
    

返回值为零的原因是,如果您在'onCreate()'中调用此方法,则ImageButton 尚未创建。 您可以使用 ViewTreeObserver 获取位置:

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);  

    } 
});

编码愉快

获取 onWindowFocusChanged() 上的值。

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

    ImageButton imagebutton = (ImageButton) findViewById(R.id.imagebutton);
    int[] posXY = new int[2];
    imagebutton.getLocationInWindow(posXY);
    int x = posXY[0];
    int y = posXY[1];

    Log.d("X and Y Point", x + " " + y);
}

post() 在 setContentView() 之后调用。

方法 setContentView() 在顶视图的 callingViewGroup.addView() 中结束,addView() 调用总是触发 requestLayout()。反过来,requestLayout() post 是主线程的任务,稍后将执行。此任务将在视图层次结构上执行测量和布局。现在,如果您 post 另一个任务,它将被放入布局后任务队列中,结果,总是执行后测量和布局发生。因此,您将始终拥有有效尺寸。

取自

button.post(new Runnable() {
    @Override
    public void run() {
        // get coordinates
    }
});