资源描述:
《AndroidgetWidth和getMeasuredWidth的正解》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、一。也許很多童鞋對getWidth()和getMeasuredWidth()的用法有很多的不解,這兩者之間有什麼樣的不同呢,網上也有各種不同的版本,但大多數都大同小異,從這個地方Ctrl+C,到另一個地方Ctrl+V,沒有把問題說透,也有一部分文章誤導了大家對這兩個方法的認識,我也是深受其害。這裡先糾正下面的一個版本的說法,Baidu上一搜一大堆的,可惜這種說法是錯的,所以希望大家就不要再盲目的轉載到你的空間裡:getWidth得到是某个view的实际尺寸.getMeasuredWidth是得到某view想要
2、在parentview里面占的大小.想必你也見過這樣的解釋,聽起來這樣的解釋也似雲裡霧裡,沒有把問題點透。二。好了,錯誤的版本就不過多說了,下面對這兩個方法做一下正解,首先大家應先知道以下幾點:1.在一個類初始化時,即在構造函數當中我們是得不到View的實際大小的。感興趣的朋友可以試一下,getWidth()和getMeasuredWidth()得到的結果都是0.但是我們可以從onDraw()方法裡面得到控件的大小。2.這兩個方法所得到的結果的單位是像素即pixel.對兩個方法做介紹:getWidth():得
3、到的是view在父Layout中佈局好後的寬度值,如果沒有父佈局,那麼默認的父佈局是整個屏幕。也許不好理解。通過一個例子來說明一下。例1:publicclassTestextendsActivity{privateLinearLayoutmBackgroundLayout;privateTextViewTestmTextViewTest;/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanc
4、eState){super.onCreate(savedInstanceState);mBackgroundLayout=newMyLayout(this);mBackgroundLayout.setLayoutParams(newLinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT));mTextViewTest=newTextViewTest(this);m
5、BackgroundLayout.addView(mTextViewTest);setContentView(mBackgroundLayout);}publicclassMyLayoutextendsLinearLayout{publicMyLayout(Contextcontext){super(context);//TODOAuto-generatedconstructorstub}@OverrideprotectedvoidonLayout(booleanchanged,intl,intt,intr,
6、intb){//TODOAuto-generatedmethodstubsuper.onLayout(changed,l,t,r,b);Log.i("Tag","--------------");ViewmView=getChildAt(0);mView.measure(0,0);}}publicclassTextViewTestextendsTextView{publicTextViewTest(Contextcontext){super(context);//TODOAuto-generatedconst
7、ructorstubsetText("testtest");}@OverrideprotectedvoidonDraw(Canvascanvas){//TODOAuto-generatedmethodstubsuper.onDraw(canvas);//measure(0,0);Log.i("Tag","width:"+getWidth()+",height:"+getHeight());Log.i("Tag","MeasuredWidth:"+getMeasuredWidth()+",MeasuredHei
8、ght:"+getMeasuredHeight());}}}這裡是在LinearLayout裡添加一個TextView控件,如果此時要得到對TextView獲取getWidth(),那麼是在TextView添加到Layout後再去獲取值,並不單單的是對TextView本身寬度的獲取。getMeasuredWidth():先看一下API裡面怎麼說的Thewidthofthisviewasmeasure