gpt4 book ai didi

java - getLocationOnScreen 崩溃

转载 作者:行者123 更新时间:2023-12-02 08:11:59 26 4
gpt4 key购买 nike

我需要获取应用程序在屏幕上的坐标,以将它们用作弹出窗口的偏移量。

                    View tempView = (View) findViewById(R.layout.main);
int[] loc = {0,0};
tempView.getLocationOnScreen(loc); /// crashes here!

尝试了这段代码,但它的最后一行使应用程序崩溃。也许我从主布局获得的 tempView 与屏幕上的布局不符?

任何建议...谢谢! :)

<小时/>

补充:已解决

                    int[] loc = new int[2]; 
View tempView = (View) findViewById(R.id.LL_whole);
tempView.getLocationOnScreen(loc);

post( String.valueOf(loc[1]) );

有效! :)

最佳答案

尝试检查 tempView 是否为 null。我怀疑 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>

所以你想说:

SomeView v = (SomeView)findViewById(R.id.myView);  

或者也许:

SomeLayout l = (SomeLayout)findViewById(R.id.myLayout);

关于java - getLocationOnScreen 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7230823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com