解决在onCreate()过程中获取View的width和Height为0的4种方法
生活随笔
收集整理的這篇文章主要介紹了
解决在onCreate()过程中获取View的width和Height为0的4种方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
此博客為轉載,原文請看這位老鐵的文章:?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() {@Overridepublic 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() {@Overridepublic void run() {view.getHeight(); //height is ready }});
3、重寫View的onLayout方法
?
view = new View(this) {@Overrideprotected 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()
?
轉載于:https://www.cnblogs.com/Oldz/p/9341452.html
總結
以上是生活随笔為你收集整理的解决在onCreate()过程中获取View的width和Height为0的4种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS中的7种设计模式
- 下一篇: Java中byte与16进制字符串的互相