getLocationOnScreen() 返回零

9
我正在使用以下代码来获取按钮的位置,但它总是返回零。为什么会发生这种情况?
    Button b=(Button) findViewById(R.id.button2);
    final int[] x=new int[2];
    b.getLocationOnScreen(x);

我相信这里会有人可以帮助我。

你在哪里调用上面的代码?是在onCreate()方法中吗? - Gopal Gopi
这取决于您是在创建布局之后还是在活动中创建布局之前调用此函数。 - Bharat Sharma
2
请查看我在这里的答案(http://stackoverflow.com/questions/19525945/getlocationonscreen-of-a-child-of-gridlayout/19526211#19526211)。您的问题将会得到解决。 - Naddy
1个回答

17

试一试...

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接