Android 自定義View 學習

Android 每一個控件都會在屏幕上占據一個矩形,而控件大體上可分為2類 View 和ViewGroup

View樹結構.png

ViewGroup是View的子類,一個ViewGroup控件中可以有一個或多個View控件(如一個layout中有多個button ),通過ViewGroup,整個界面上的控件形成一個樹形結構,上層控件負責子控件的測量和繪制,并傳遞交互事件。

View的測量

如果我們要畫一個圖形,就要知道它的大小和位置,那么就要有一個坐標系


Android坐標軸.png

之前說過Android每一個控件都占據了一個矩形,那么每一個矩形的左上角也是這個控件的原點。

有了坐標系就可以為測量做準備了,但是控件的測量并不是這么簡單
View的測量是在 onMeasure()方法中進行的

Android 提供給我們一個MeasureSpec類,幫助我們測量MeasureSpec作為int類型實現,而減少對象開銷,它一共32位int 高兩位是mode,低30位是測量的大小。
模式一共有3種,UNSPECIFIED, EXACTLY, AT_MOST

  • UNSPECIFIED 模式

The parent has not imposed any constraint on the child. It can be whatever size
it wants.
父View 沒有約束大小,它可以是任意大小

  • EXACTLY

The parent has determined an exact size for the child. The child is going to be
given those bounds regardless of how big it wants to be.
精確模式,當我們將控件的layout_width 屬性和layout_height屬性提供確切大小
或者是占據父View大小 ,使用這種模式

 <Button
    android:layout_width="match_parent"
    android:layout_height="100dp"/>
  • AT_MOST

The child can be as large as it wants up to the specified size.
最大值模式,當我們將控件的layout_width 屬性和layout_height屬性
指定為wrap_content,一般隨著子控件或內容的變化而變化

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is third child view"/>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容