4種Android獲取View寬高的方式
有時(shí)我們會(huì)有基于這樣的需求,當(dāng)Activity創(chuàng)建時(shí),需要獲取某個(gè)View的寬高,然后進(jìn)行相應(yīng)的操作,但是我們?cè)趏nCreate,onStart中獲取View的大小,獲取到的值都是0,只是由于View的繪制工程還未完成,和在onCreate中彈出Dialog或者PopupWindow會(huì)報(bào)一個(gè)Activity not running原理類似。
接下來就為大家介紹幾種獲取View寬高的方法:
第一種方式:重寫Activity中的onWindowFocusChanged,當(dāng)Activity獲取到焦點(diǎn)的時(shí)候View已經(jīng)繪制完成,也能獲取到View的準(zhǔn)確寬高了。同樣的Dialog和PopupWindow也可以在這里彈出,需要注意的是這個(gè)方法會(huì)調(diào)用多次,當(dāng)hasFocus為true時(shí),才可進(jìn)行相應(yīng)的操作
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { System.out.println("onWindowFocusChanged width=" + tvTest.getWidth() + " height=" + tvTest.getHeight()); } }
第二種方式:
/** * 會(huì)執(zhí)行多次 */ private void getSize1() { ViewTreeObserver vto = tvTest.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { int height = tvTest.getMeasuredHeight(); int width = tvTest.getMeasuredWidth(); System.out.println("height" + height); System.out.println("width" + width); return true; } }); }
第三種方式:
private void getSize2() { ViewTreeObserver viewTreeObserver = tvTest.getViewTreeObserver(); viewTreeObserver .addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { tvTest.getViewTreeObserver() .removeGlobalOnLayoutListener(this); System.out.println("onGlobalLayout width=" + tvTest.getWidth() + " height=" + tvTest.getHeight()); } }); }
第四種方式:
private void getSize3() { tvTest.post(new Runnable() { @Override public void run() { System.out.println("postDelayed width=" + tvTest.getWidth() + " height=" + tvTest.getHeight()); } }); }
以上就是Android獲取View寬高的4種方式,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
android實(shí)現(xiàn)點(diǎn)擊按鈕切換不同的fragment布局
這篇文章主要為大家詳細(xì)介紹了android實(shí)現(xiàn)點(diǎn)擊按鈕切換不同的fragment布局,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12android 監(jiān)聽SD卡文件變化的實(shí)現(xiàn)代碼
這篇文章主要介紹了android 監(jiān)聽SD卡文件變化的實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-11-11Android 中RxPermissions 的使用方法詳解
這篇文章主要介紹了Android 中RxPermissions 的使用方法詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-10-10Android UI實(shí)時(shí)預(yù)覽和編寫的各種技巧
大家好,今天給大家分享的是Android中實(shí)時(shí)預(yù)覽UI和編寫UI的各種技巧,2015-11-11Android 懸浮窗權(quán)限各機(jī)型各系統(tǒng)適配大全(總結(jié))
這篇文章主要介紹了Android 懸浮窗權(quán)限各機(jī)型各系統(tǒng)適配大全(總結(jié)),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08Android仿iOS實(shí)現(xiàn)側(cè)滑返回功能(類似微信)
這篇文章主要為大家詳細(xì)介紹了Android仿iOS實(shí)現(xiàn)側(cè)滑返回功能,類似微信功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12Android實(shí)現(xiàn)錄音方法(仿微信語(yǔ)音、麥克風(fēng)錄音、發(fā)送語(yǔ)音、解決5.0以上BUG)
大家平時(shí)在使用微信qq聊天時(shí)經(jīng)常會(huì)發(fā)送語(yǔ)音功能,今天小編給大家?guī)砹嘶赼ndroid實(shí)現(xiàn)錄音的方法仿微信語(yǔ)音、麥克風(fēng)錄音、發(fā)送語(yǔ)音、解決5.0以上BUG,需要的朋友參考下吧2018-04-04