Java getLocationOnScreen崩溃
我需要在屏幕上获取我的应用程序的坐标,以便将它们用作弹出窗口的偏移量Java getLocationOnScreen崩溃,java,android,Java,Android,我需要在屏幕上获取我的应用程序的坐标,以便将它们用作弹出窗口的偏移量 View tempView = (View) findViewById(R.layout.main); int[] loc = {0,0}; tempView.getLocationOnScreen(loc); /// crashes here! 尝试了此代码,但最后一行代码使应用程序崩溃。也许我从主布局中
View tempView = (View) findViewById(R.layout.main);
int[] loc = {0,0};
tempView.getLocationOnScreen(loc); /// crashes here!
尝试了此代码,但最后一行代码使应用程序崩溃。也许我从主布局中获得的tempView与屏幕上的布局不一致
任何建议。。。谢谢!:)
增加: 解决
工作!:) 尝试检查tempView是否为空。我怀疑findViewById()找不到您给它的id
int[] loc = {0,0};
View tempView = (View) findViewById(R.layout.main);
if (tempView != null) {
tempView.getLocationOnScreen(loc);
} else {
Log.d("YourComponent", "tempView was null.");
}
在XML中有如下内容:
<SomeLayout android:id="@+id/myLayout" ... >
<SomeView android:id="@+id/myView" ... />
<SomeOtherView android:id="@+id/myOtherView" .../>
</SomeLayout>
或许:
SomeLayout l = (SomeLayout)findViewById(R.id.myLayout);
findViewById(R.layout.main)
您应该在此处放置R.id.something,而不是R.layout.something。是,给出空值。:)我是否应该找到其他的视图id,而不是主视图?是的,您要查找的视图id。
SomeView v = (SomeView)findViewById(R.id.myView);
SomeLayout l = (SomeLayout)findViewById(R.id.myLayout);