2013-03-28 26 views
7

我在Linearlayout.LinearLayout中通過編程方式在View中添加View(按鈕)。什麼時候應該在片段中獲得寬度視圖

我想按鈕的寬度,但總是返回0。

我GOOGLE了這個問題,

工作的getWidth僅onWindowFocusChanged。

public void onWindowFocusChanged(boolean hasFocus) { } 

但是Fragment沒有這個方法。

如何獲得在片段中的查看寬度?

回答

8

退房信息GlobalLayoutListener。您可以使用Button中的聽衆onCreateView(),因爲您已使用onWindowFocusChanged。它也比onWindowFocusChanged()更可靠。

試試如下:

final View myView = profileContainer.findViewById(R.id.sub_page_padding); 
    ViewTreeObserver vto = profilePadding.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     Log.d("TEST", "Height = " + myView.getHeight() + " Width = " + myView.getWidth()); 
     ViewTreeObserver obs = profilePadding.getViewTreeObserver(); 
     obs.removeGlobalOnLayoutListener(this); 
    } 
    }); 
5

我也有類似的問題,並在片段回調onViewCreated解決它()是這樣的:

@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 
    view.post(new Runnable() { 
     @Override 
     public void run() { 
      // do operations or methods involved 
      // View.getWidth(); or View.getHeight(); 
      // here 
     } 
    }); 
} 

的run()在所有視圖呈現後運行...

相關問題