在activity生命周期方法:onCreate(),onStart(),onResume()中調用View.getWidth()和View.getHeight()方法獲取View的高度是不可行的,因為此時布局沒有加載是不可見狀態。
還有當view的可見狀態為:GONE,時獲取的寬高也是0;
2. 解決辦法:
(1)直接測量:
private void first() {
int width = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
int height = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
textView.measure(width, height);
int height1 = textView.getMeasuredHeight();
int width3 = textView.getMeasuredWidth();
System.out.println("first: 寬: " + width3 + " 高: " + height1);
}(2)添加繪制view之前的監聽
private void second() {
ViewTreeObserver vto = textView.getViewTreeObserver();
vto.addOnPreDrawListener(new
ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
int height = textView.getMeasuredHeight();
int width = textView.getMeasuredWidth();
System.out.println("second: 寬:" + width + " 高: " + height);
return true;
}
});
}(3)添加整體布局監聽
private void third() {
ViewTreeObserver vto = textView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
textView.getViewTreeObserver().removeGlobalOnLayoutListener(
this);
int height = textView.getMeasuredHeight();
int width = textView.getMeasuredWidth();
System.out.println("third: 寬:" + width + " 高: " + height);
}
});
}免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。