Android 自定义 View 浅析
概括
说到自定义 View ,就一定得说说 android 系统的UI绘制流程。再说这个流程之前,我们先看一下在每一个 activity 页面中我们的布局 ui 所处的位置。
从上图就可以知道,我们平时使用的 setContentView()
这个方法就是用来设置 contentview
的。了解了,这个之后,我们还应该了解一下 android 中 view 的继承关系。
从上面的一张图中,我们可以看出 android 的 UI 控件主要有两种:view 和 viewgroup。那么像我们经常使用的 Button
,TextView
,ImageView
都属于 view 的范畴!FrameLayout
,LinearLayout
等都属于 viewgroup 的范畴!了解了这些基本知识之后,我们再来说说如果自定义控件!
如何自定义
我们要自定义控件,无非就是继承 view 或者 viewgroup 亦或者继承已有的控件在上面在进行扩展!在这里继承 view 和 继承 viewgroup 有点区别!我们先来说说相同点吧!
相同点
1. 初始化
这个其实就是构造函数啦,在这里你可以为这个 view 设置特定的属性啊!那么如何自定义属性呢?首先你得在 res
-->
values
这个目录下新建 attrs
的资源文件!在这个文件中配置你要的自定义属性!先看一下代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="WeekSelectView">
<attr name="selectColor" format="color"></attr>
<attr name="unSelectColor" format="color"></attr>
<attr name="lineColor" format="color"></attr>
<attr name="textColor" format="color"></attr>
<attr name="textSize" format="dimension"></attr>
<attr name="selectSize" format="dimension"></attr>
<attr name="lineWidth" format="dimension"></attr>
<attr name="lineHeight" format="dimension"></attr>
<attr name="space" format="dimension"></attr>
</declare-styleable>
</resources>
其中的 declare-styleable
标签就是添加自定义属性用的,里面包含的每一个 attr
就代表每一个自定义属性!后天面的 format
属性代表每一个属性的类型!接着就是我该如何使用它们呢!我们只要在布局文件中使用代码就行了:
<com.kidbot.library.widget.weekselect.WeekSelectView
xmlns:weekselect="http://schemas.android.com/apk/res-auto"
android:id="@+id/weekselect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
weekselect:lineHeight="10dp"
weekselect:lineWidth="50dp"
weekselect:selectSize="10dp"
weekselect:space="30dp"
weekselect:textSize="15sp" />
要注意的是如果要在布局文件中使用这些自定义属性得加这句话: xmlns:weekselect="http://schemas.android.com/apk/res-auto" 其中 weekselect 这个字段属于用户自定义!
好了知道如何使用了,那么在写自定义 view 的时候,我们该怎么获取这些这些值呢?
TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.WeekSelectView);
selectColor=typedArray.getColor(R.styleable.WeekSelectView_selectColor, Defalut_Select_Color);
unSelectColor=typedArray.getColor(R.styleable.WeekSelectView_unSelectColor, Defalut_UnSelect_Color);
lineColor=typedArray.getColor(R.styleable.WeekSelectView_lineColor, Defalut_Line_Color);
textSize = typedArray.getDimension(R.styleable.WeekSelectView_textSize, Defalut_Text_Size);
textColor = typedArray.getColor(R.styleable.WeekSelectView_textColor, Defalut_Text_Color);
selectSize = typedArray.getDimension(R.styleable.WeekSelectView_selectSize, Defalut_Select_Size);
lineHeight = typedArray.getDimension(R.styleable.WeekSelectView_lineHeight, Defalut_Line_Height);
lineWidth=typedArray.getDimension(R.stylea