Nad*_*ddy 15 android android-layout
我想以ImageView编程方式获得我的位置.按位置,我的意思是从屏幕顶部到ImageView.我在堆栈溢出中发布的所有其他解决方案的像素距离,但它对我不起作用.我的最低API级别是8.
这些是我试过的代码 -
ImageView image = (ImageView) findViewById(R.id.imageView1);
1) image.getTop();
2) private int getRelativeTop(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getTop();
else
return myView.getTop() + getRelativeTop((View) myView.getParent());
}
3) image.getLocationOnScreen(int[] locaiton);
Run Code Online (Sandbox Code Playgroud)
Car*_*nal 48
当布局与子视图一起放置时,您需要等待回调.这是您需要添加到根视图以便计算图像坐标的侦听器.否则它将返回0.
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
image.getLocationOnScreen(locations);
int x = locations[0];
int y = locations[1];
}
});
Run Code Online (Sandbox Code Playgroud)
仅在视图布局后使用View.getLocationOnScreen()或仅使用.,,并返回相对于其父的位置.getLocationInWindow() getTop()getLeft()getBottom()getRight()