android获取控件宽度高度
前幾天,在自定義控件的時候碰到個問題,就是在如何獲取自定義控件的高寬。在自定義控件類的構造函數中,本來以為可以輕松獲取,但事實不是這樣。我測試了下面代碼:?
先是布局代碼:?
<com.lml.getvalues.MyView?
? ? ? ? android:id="@+id/myView"?
? ? ? ? android:layout_width="match_parent"?
? ? ? ? android:layout_height="150px"?
? ? ? ? android:background="#ff0000" />?
再是MyView的構造函數的代碼:?
public MyView(Context context, AttributeSet attrs) {?
super(context, attrs);?
a="在MyView構造函數中 : MeasuredWidth:"+this.getMeasuredWidth()+";"+"MeasuredHeight:"+this.getMeasuredHeight()+";"?
+"Width:"+this.getWidth()+";"+"Height:"+this.getHeight()+"\n";?
String h="",w="";?
for(int i =0 ;i < attrs.getAttributeCount();i++){?
if("layout_height".equals(attrs.getAttributeName(i))){?
h=attrs.getAttributeValue(i);?
}else if("layout_width".equals(attrs.getAttributeName(i))){?
w=attrs.getAttributeValue(i);?
}?
}?
b="在構造函數attrs中 : ?width:"+w+";"+"height:"+h+"\n";?
}?
編譯得到a="在MyView構造函數中 : MeasuredWidth:0;MeasuredHeight:0;Width:0;Height:0".?
b="在構造函數attrs中 : ?width:-1;height:150.0px?
結果顯示當width為match_parent等數值時,只顯示-1等,不能滿足我的需求。?
然后我試著在相應Activity的onCreate中獲取高寬,獲得的全部是0.但我在onCreate中的加了個點擊控件獲取高寬事件,能正確獲取高寬。我在網上查了下資料,因為在onCreate中控件還未被度量,所以獲取肯定為0.網上有獲取三個方法,方法如下:?
方法一不知道為何,在我這實現不了,咋onCreate中添加如下代碼:?
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);?
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);?
myView.measure(w, h);?
int height = myView.getMeasuredHeight();?
int width = myView.getMeasuredWidth();?
tvValues.append("方法一: height:"+height + ",width:" + width+"\n");?
方法二可以實現,代碼如下:?
ViewTreeObserver vto2 = myView.getViewTreeObserver();?
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {?
@Override?
public void onGlobalLayout() {?
myView.getViewTreeObserver().removeGlobalOnLayoutListener(this);?
tvValues.append( "方法二: height:"+myView.getHeight() + ",width:" + myView.getWidth()+"\n");?
}?
});?
但我發現removeGlobalOnLayoutListener在API 級別 16 開始已經廢棄,如果去掉,系統會讀取多次。?
再來看看方法三,代碼如下:?
ViewTreeObserver vto = myView.getViewTreeObserver();?
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {?
public boolean onPreDraw() {?
myView.getViewTreeObserver().removeOnPreDrawListener(this);?
int height = myView.getMeasuredHeight();?
int width = myView.getMeasuredWidth();?
tvValues.append("方法三: height:"+height + ",width:" + width + "..\n");?
return true;?
}?
});?
我在網上資料的基礎上添加了myView.getViewTreeObserver().removeOnPreDrawListener(this);這一條,這個可以保證系統運行一次。
轉載于:https://blog.51cto.com/tongfu1013/1680753
總結
以上是生活随笔為你收集整理的android获取控件宽度高度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星s9 android 版本,三星S9
- 下一篇: eclipse字体大小调整