2012-07-02 35 views
2

我有一個包含TextView調用的片段作爲mTextView。我想以後追加內容,它在片段的onCreateView這樣得到mTextView的高度:當片段onCreateView時無法獲取TextView的高度

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     final View view = inflater.inflate(
       R.layout.myfragment, container, false); 

     mTextView = (TextView) view.findViewById(R.id.myTextView); 
       int mHeight=mTextView.getHeight(); 

} 

但它總是返回0值。

+2

使用下面的鏈接,http://adanware.blogspot.in/2012/06/android-getting-measuring-fragment.html –

回答

0

你嘗試之後

setContentView(R.layout.your_layout); 

有權得到它?

+0

是,檢查我的編輯:( –

0

如果您嘗試在onCreate後立即獲取高度,您將無法獲取,因爲該窗口仍未聚焦。嘗試像這樣:

@Override 
public void onWindowFocusChanged(boolean hasFocus) { 
    // your code here 
    int mHeight=mTextView.getHeight(); 
} 
+0

我試試看吧在我的fragment類中看不到onWindowFocusChanged方法:( –

+0

哦,那麼你需要使用消息處理程序來獲得正確的高度。在你的fragment類中設置一個消息處理程序,延遲1秒,一旦處理程序觸發try內部處理程序如果你仍然不能讓我知道.. –

+0

我認爲,但我認爲這不是一個很好的解決方案來解決這個問題:( –

0

視圖的維數爲0的原因是因爲當你查詢它們時,視圖仍然沒有執行佈局和測量步驟。你只是告訴視圖如何在佈局中「表現」,但它仍然沒有計算出每個視圖的放置位置。

雖然有一些技巧可以獲得這個尺寸。儘管我不太喜歡接受的答案,但您可以將此問題作爲一個起點。

How to get the width and height of an android.widget.ImageView?

+0

謝謝,我會看那個話題。 –