<RelativeLayout
android:layout_width="48dp"
android:layout_height="48dp"
android:id="@+id/book_mark"
android:clipChildren="false"
custom:layoutBackground="#00000000"
android:gravity="center">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:id="@+id/book_mark_image"
android:src="@drawable/icon_bookmark"/>
</RelativeLayout>
我的布局xml上面。当我调用imageview.getY()时,结果为0。当我运行这个应用程序时,ImageView实际上以RelativeLayout为中心。但是getY()返回0.根据布局的大小,imageView到relativeLayout的距离应该是9dp,所以getY()应该返回(9dp - &gt; px)。谁知道发生了什么?
答案 0 :(得分:0)
请先确保您的图像可见性不会消失
否则这是因为你很可能在创建或恢复时调用了getY() 问题是您的图像尚未加载以了解图像视图的确切位置,现在您可以使用观察者
ViewTreeObserver viewTreeObserver = image1.getViewTreeObserver();
viewTreeObserver
.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//now get width or position
//and don't forget to remove listener
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
image1.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
else
image1.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
});