日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

android获取控件宽度高度

發布時間:2023/12/10 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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获取控件宽度高度的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。