簡體   English   中英

GridLayout子節點的getLocationOnScreen

[英]getLocationOnScreen of a child of GridLayout

我試圖在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"  />

繼承人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()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);
    } 
});

布局放置子視圖時,您需要等待回調。 您使用的代碼返回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];
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM