1. 程式人生 > >解決在onCreate()過程中獲取View的width和Height為0的4種方法

解決在onCreate()過程中獲取View的width和Height為0的4種方法

得到 observer oba target 都沒有 重寫 idt tlist reat

此博客為轉載,原文請看這位老鐵的文章: https://www.cnblogs.com/kissazi2/p/4133927.html

很經常當我們動態創建某些View時,需要通過獲取他們的width和height來確定別的view的布局,但是在onCreate()獲取view的width和height會得到0.view.getWidth()和view.getHeight()為0的根本原因是控件還沒有完成繪制,你必須等待系統將繪制完View時,才能獲得。這種情況當你需要使用動態布局(使用wrap_content或match_parent)就會出現。一般來講在Activity.onCreate(...)、onResume()方法中都沒有辦法獲取到View的實際寬高。所以,我們必須用一種變通的方法,等到View繪制完成後去獲取width和Height。下面有一些可行的解決方案。

1、監聽Draw/Layout事件:ViewTreeObserver

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
          @Override
          public void onGlobalLayout() {
              mScrollView.post(new Runnable() {
                  public void run() {
                      view.getHeight(); //height is ready
              //do something
} }); } });

2、將一個runnable添加到Layout隊列中:View.post()

final View view=//smth;
...
view.post(new Runnable() {
            @Override
            public void run() {
                view.getHeight(); //height is ready
            }
        });

3、重寫View的onLayout方法

view = new View(this) {
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        view.getHeight(); //height is ready
    }
};

4, 附加:獲取固定寬高

如果你要獲取的view的width和height是固定的,那麽你可以直接使用:

1 View.getMeasureWidth()
2 View.getMeasureHeight()

解決在onCreate()過程中獲取View的width和Height為0的4種方法