關鍵點:獲取寬高應該在view的onLayout之后,這個時候,view已經確定算出寬高。 error:
/** * 在onCreate,onResume方法中調用,用于獲取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正確時機: 1.在監聽事件中獲?。?/p>/** * 這里的button1是我們定義的Button組件,并且我們重寫了Button的點擊事件,在其中調用了獲取組件寬高的方法 */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); /** * 當hasFocus為true的時候,說明Activity的Window對象已經獲取焦點,進而Activity界面已經加載繪制完成 */ if (hasFocus) { int widht = titleText.getWidth(); int height = titleText.getHeight(); Log.i(TAG, "onWindowFocusChanged width:" + widht + " " + " height:" + height; } }3.為組件添加OnGlobalLayoutListener事件監聽
/** * 為Activity的布局文件添加OnGlobalLayoutListener事件監聽,當回調到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, "開始執行onGlobalLayout()........."); int height = titleText.getMeasuredHeight(); int width = titleText.getMeasuredWidth(); Log.i(TAG, "height:" + height + " width:" + width); // 移除GlobalLayoutListener監聽 MainActivity.this.getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); }4.使用View.post方法獲取組件的寬高
/** * 使用View的post方法獲取組件的寬度和高度,這里用的是異步消息獲取組件的寬高,而這里的異步消息的執行過程是在主進程的主線程的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); } }); }新聞熱點
疑難解答