一、根据需要自定义View的一些属性
在values/attrs.xml文件中自定义属性
<resources>
<attr name="titleContent" format="string"/>
<attr name="titleTextColor" format="color"/>
<attr name="titleTextSize" format="dimension"/>
<declare-styleable name="CustomTitleView">
<attr name="titleContent"/>
<attr name="titleTextColor"/>
<attr name="titleTextSize"/>
</declare-styleable>
</resources>
在上面我们定义了文字内容、字体颜色和字体大小3个属性,format是指该属性的取值的类型,有“reference”(引用)、“color”(颜色)、“boolean”(布尔型)、“dimension”(尺寸)、“float”(浮点型)、“integer”(整型)、“string”(字符串)、“fraction”(百分数)、“flag”(标记)、”enum”(枚举型)等
declare-styleable可以看做是attr的一个集合,通过obtainStyledAttributes方法获取,返回的是一个TypedArray数组。
二、继承View,实现构造函数
自定义View的构造函数具体怎么用(根据官网的说法)
/**
* Simple constructor to use when creating a view from code.
*/
public View(Context context) //在代码中使用自定义View时调用
/**
* Constructor that is called when inflating a view from XML. This is called
* when a view is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
*/
public View(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
} //在xml文件(一般是布局文件)中使用自定义view时调用,属性值在xml文件中定义,主题保持跟Context的主题一致
/**
* Perform inflation from XML and apply a class-specific base style from a
* theme attribute. This constructor of View allows subclasses to use their
* own base style when they are inflating. For example, a Button class's
* constructor would call this version of the super class constructor and
* supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
* allows the theme's button style to modify all of the base view attributes
* (in particular its background) as well as the Button class's attributes.
*/
public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
//这个构造函数也是在xml中使用自定义的view时调用,增加了自己定义的style,一般情况下由两个参数的构造函数调用此构造函数
三、实现onMeasure方法
View.MeasureSpec中测量模式有三种:
EXACTLY:一般是设置了明确的值或者是MATCH_PARENT
AT MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT
UNSPECIFIED:表示子布局想要多大就多大,很少使用
注意:如果对View的宽高进行修改了,不要调用super.onMeasure(widthMeasureSpec,heightMeasureSpec);要调用setMeasuredDimension(widthsize,heightsize); 这个函数。