我试图获取 GridLayout 中图像视图的 x/y,但我的日志一直显示X & Y: 0 0
有任何想法吗?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/root" >
...
<GridLayout
android:id="@+id/gridLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:columnCount="3"
android:rowCount="5" >
...
<ImageView
android:id="@+id/fivetwo"
android:layout_width="75dp"
android:layout_height="75dp"
android:contentDescription="@string/gameboard"
android:gravity="center"
android:src="@drawable/tile"
android:layout_columnSpan="1"
android:layout_rowSpan="1" />
这是java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
....
ImageView temp = (ImageView) findViewById(R.id.fivetwo);
int originalPos[] = new int[2];
temp.getLocationOnScreen( originalPos );
Log.i(TAG, "X & Y: " + originalPos[0] + " " + originalPos[1]);
...
记住:getX()
and getY()
return 0
如果组件尚未绘制(在 onCreate(){} 中).
找出a的位置view
一旦准备好:
将树观察器添加到布局中。这应该返回正确的位置。
onCreate 在子视图布局完成之前调用。所以宽度和高度还没有计算出来。获取高度和宽度。将其放在 onCreate 方法上
final ImageView temp = (ImageView) findViewById(R.id.fivetwo);
ViewTreeObserver vto = temp.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
temp.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int x = temp.getX();
int y = temp.getY();
Log.v(TAG, String.format("X:%d Y:%d",x,y);
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)