美文网首页
Android 自定义View 学习

Android 自定义View 学习

作者: siyanGo | 来源:发表于2017-05-22 19:54 被阅读22次

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"/>

相关文章

网友评论

      本文标题:Android 自定义View 学习

      本文链接:https://www.haomeiwen.com/subject/nofixxtx.html