在Android中的视图(ImageButton)的X和Y坐标都获得0值 [英] Getting 0 Value for both X and Y Coordinate of view(Imagebutton) in android

查看:115
本文介绍了在Android中的视图(ImageButton)的X和Y坐标都获得0值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得X和Y的视角(图像按钮).

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

当我尝试使用下面的代码在Click事件上找到X和Y时,我将获得View的正确X和Y坐标.

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

    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.

But I want X and Y Co-ordinate before Click on view so I try to get X and Y with below code.

    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?

But whenever I try to get X and Y with ClickListener I get X and Y as 0 and 0. So, I do not get Proper X and Y without ClickListener. Could anyone help to solve out what is an actual issue, how can I get Proper X and Y without ClickListener?

推荐答案

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

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

    } 
});

快乐编码

这篇关于在Android中的视图(ImageButton)的X和Y坐标都获得0值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆