2012-01-16 27 views
8

此問題已被多次詢問,但每個人都給出了發生這種情況的原因(即計算在佈局之前發生)。但我需要這個解決方案。我試過getBottom();,getTop();,getLocationOnScreen(int[] location);。但是全部返回值零(0)。我甚至嘗試在onStart();中給予這些,給佈局鋪平了時間,但沒有運氣。 這裏是我的代碼:獲取視圖位置的方法返回0

TextView tv; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tv = (TextView) findViewById(R.id.textView1); 
    Log.d("getBottom :", Integer.toString(tv.getBottom())); 
    Log.d("gettop  :", Integer.toString(tv.getTop())); 

    int[] location = new int[2]; 
    tv.getLocationOnScreen(location); 
    Log.d("getlocationonscreen values :", Integer.toString(location[0])+" "+Integer.toString(location[1])); 
} 
@Override 
protected void onStart() { 
    Log.d("getBottom in onStart :", Integer.toString(tv.getBottom())); 
    Log.d("gettop in onStart :", Integer.toString(tv.getTop())); 

    int[] location = new int[2]; 
    tv.getLocationOnScreen(location); 
    Log.d("getlocationonscreen in onStart :", Integer.toString(location[0])+" "+Integer.toString(location[1])); 
    super.onStart(); 
} 

佈局XML:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="156dp" 
    android:text="Medium Text" 
    android:textAppearance="?android:attr/textAppearanceMedium" /> 

</RelativeLayout> 

同樣,我對重複的問題表示歉意。提前致謝。

+0

請問您能解釋一下您的具體問題。上面的代碼中會出現什麼問題。 – 2012-01-16 11:45:26

回答

13

您將'測量'放在onWindowFocusChanged()-方法中。
由於文檔狀態:

這是該活動是否對用戶可見的最佳指標。

你也可以把它放在onResume()這是應用程序之前的最後一步完全是在屏幕上活躍,但是:

記住的onResume是不是最好的指標,你的活動對用戶可見;系統窗口(如鍵盤)可能在前面。使用onWindowFocusChanged(boolean)可以確定您的活動對用戶是可見的(例如,恢復遊戲)。

如果尚未顯示窗口/視圖,則不能保證它具有其測量值,因此以前的方法會更好。