說了這麼多,那View的大小是多少呢?這小節我就研究下View的大小。通過LogCat來研究View的大小是怎樣確定的。好了,直接切入正題吧.
一、 在Activity中直接new HelloView時View的大小。
View的大小擷取可以用其中的兩種方法擷取:
this.getHeight():擷取View的高
this.getWidth():擷取View的寬
我們可以做一個猜想,View的大小是在什麼時候確定的,是在new一個View的時候還是在onDraw()的時候?還是在其他時候?為了研究這個,我們分別在建構函式和onDraw中打上Log補丁(這個只是個人習慣的稱呼)。
--- >HelloVew.java
publicHelloView(Context context){ super(context); Log.v("HelloView(Context context)",""+ this.getHeight()+ " "+ this.getWidth()); } /** *這個是我們要在XML中初始化用的 **/ publicHelloView(Context context,AttributeSet attrs){ super(context, attrs); Log.v("HelloView(Context context,AttributeSet attrs)",""+ this.getHeight()+ " "+ this.getWidth()); } /** *繪製View **/ protectedvoidonDraw(Canvas canvas){ Log.v("onDraw(Canvas canvas)",""+ this.getHeight()+ " "+ this.getWidth()); canvas.drawColor(Color.WHITE); myUseBitmapFactory(canvas); myUseBitmapDrawable(canvas); myUseInputStreamandBitmapDrawable(canvas); } |
運行:
我們觀察可以發現,new View 的時候並沒有確定了View的大小,並且系統就沒有調用(Context context)這個建構函式。
也就是說View大小是在new View之後OnDraw之前確定的,那onDraw之前的又有那些方法了,呵呵,我們試著override這個方法試試:
protectedvoidonMeasure(intwidthMeasureSpec, intheightMeasureSpec) { // TODOAuto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); Log.v("onMeasure",""+ this.getHeight()+ " "+ this.getWidth()); } |
運行:
我們觀察發現:onMeasure方法運行了兩次:第一次寬和高都是0,但是第二次就變了,是不是可以說是在這個方法中確定的,但是實際上不一定會是這麼回事,這個我們放在以後研究。這裡我們只需要知道不是在new View時確定的就好了。
二、在XML中定義時View大小
這個我們直接上代碼:
main.xml檔案修改:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <view class="com.fxhy.stady.HelloView" android:layout_width="50dip" android:layout_height="120dip" /> </LinearLayout> |
mainActivity :
/** *使用自訂的View **/ publicclassMainActivity extendsActivity { publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);// 使用自訂的View } } |
運行:
我們發現,和我們Xml中定義的大小一樣,哈哈,有興趣的可以自己測試測試
http://www.bkjia.com/uploadfile/2011/1129/20111129035518886.rar
http://www.bkjia.com/uploadfile/2011/1129/20111129035518885.rar
作者 繁星皓月