GridLayout子节点的getLocationOnScreen

jca*_*uso 2 android

我试图在GridLayout中获取imageview的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"  />
Run Code Online (Sandbox Code Playgroud)

继承人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]);

...
Run Code Online (Sandbox Code Playgroud)

nan*_*ana 8

请记住:getX()getY()返回0 如果组件尚未绘制()在的onCreate({}) .


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);
    } 
});
Run Code Online (Sandbox Code Playgroud)


Nad*_*ddy 5

布局放置子视图时,您需要等待回调.您使用的代码返回0,因为在放置布局之前返回位置.使用此代码:

temp.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        getViewTreeObserver().removeGlobalOnLayoutListener(this);

        int[] locations = new int[2];
        temp.getLocationOnScreen(locations);
        int x = locations[0];
        int y = locations[1];
    }
});
Run Code Online (Sandbox Code Playgroud)