關(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); } }); }新聞熱點
疑難解答
圖片精選