2013-10-25 102 views
8

上午使用下面的代码来获取按钮的位置,但它总是返回零。 为什么这种情况发生getLocationOnScreen()返回零

Button b=(Button) findViewById(R.id.button2); 
    final int[] x=new int[2]; 
    b.getLocationOnScreen(x); 

荫肯定有人在这里可以帮助我

+0

您在哪里调用上面的代码?在onCreate()? –

+0

这取决于您是在创建布局之后还是在创建活动布局之前调用此函数。 –

+1

看到我的答案[这里](http://stackoverflow.com/questions/19525945/getlocationonscreen-of-a-child-of-gridlayout/19526211#19526211)。你的问题将得到解决。 – Naddy

回答

12

在Globel可变
Button b; 

试试这个..

然后onCreate()

b=(Button) findViewById(R.id.button2); 

之后onCreate();

@Override 
public void onWindowFocusChanged (boolean hasFocus) { 
     final int[] x=new int[2]; 
     b.getLocationOnScreen(x); 
}