国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

android獲取view寬高的時機(jī)

2019-11-08 00:21:09
字體:
供稿:網(wǎng)友

關(guān)鍵點:獲取寬高應(yīng)該在view的onLayout之后,這個時候,view已經(jīng)確定算出寬高。 error:

/** * 在onCreate,onResume方法中調(diào)用,用于獲取TextView的寬度和高度都是0 */PRivate void getTextHeightAndWidth() { // 我們定義的用于獲取寬度和高度的組件 titleText = (TextView) findViewById(R.id.text_title); int height = titleText.getHeight(); int width = titleText.getWidth(); Log.i(TAG, "height:" + height + " " + "width:" + width); }06-26 20:12:15.356 19453-19453/uuch.com.Android_viewheight I/MainActivity: height:0 width:0

正確時機(jī): 1.在監(jiān)聽事件中獲取:

/** * 這里的button1是我們定義的Button組件,并且我們重寫了Button的點擊事件,在其中調(diào)用了獲取組件寬高的方法 */button1 = (Button) findViewById(R.id.button1);button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getTextHeightAndWidth(); } });

2.重寫Activity的onWindowFocusChanged方法

/** * 重寫Acitivty的onWindowFocusChanged方法 */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); /** * 當(dāng)hasFocus為true的時候,說明Activity的Window對象已經(jīng)獲取焦點,進(jìn)而Activity界面已經(jīng)加載繪制完成 */ if (hasFocus) { int widht = titleText.getWidth(); int height = titleText.getHeight(); Log.i(TAG, "onWindowFocusChanged width:" + widht + " " + " height:" + height; } }

3.為組件添加OnGlobalLayoutListener事件監(jiān)聽

/** * 為Activity的布局文件添加OnGlobalLayoutListener事件監(jiān)聽,當(dāng)回調(diào)到onGlobalLayout方法的時候我們通過getMeasureHeight和getMeasuredWidth方法可以獲取到組件的寬和高 */private void initOnLayoutListener() { final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Log.i(TAG, "開始執(zhí)行onGlobalLayout()........."); int height = titleText.getMeasuredHeight(); int width = titleText.getMeasuredWidth(); Log.i(TAG, "height:" + height + " width:" + width); // 移除GlobalLayoutListener監(jiān)聽 MainActivity.this.getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); }

4.使用View.post方法獲取組件的寬高

/** * 使用View的post方法獲取組件的寬度和高度,這里用的是異步消息獲取組件的寬高,而這里的異步消息的執(zhí)行過程是在主進(jìn)程的主線程的Activity繪制流程之后,所以這時候可以獲取組件的寬高。 */private void initViewHandler() { titleText.post(new Runnable() { @Override public void run() { int width = titleText.getWidth(); int height = titleText.getHeight(); Log.i(TAG, "initViewHandler height:" + height + " width:" + width); } }); }
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 石河子市| 东方市| 昭平县| 新化县| 政和县| 广水市| 界首市| 乌审旗| 东兴市| 栖霞市| 六枝特区| 宝坻区| 噶尔县| 甘谷县| 祥云县| 阳江市| 怀集县| 抚顺县| 加查县| 湘潭县| 荆州市| 安福县| 商都县| 五指山市| 平凉市| 望城县| 旺苍县| 昌图县| 探索| 南投县| 手游| 东乌| 绿春县| 阿勒泰市| 义马市| 阳城县| 平乡县| 绥化市| 仲巴县| 武陟县| 临澧县|