在自定义View的过程中,最先需要了解View的四种构造方法的使用条件以及参数。
四种构造方法如下:
/**
* 使用代码 new 创建时使用
*/
public StatusBar(Context context) {
this(context, null);
}
/**
* 使用布局文件加载时使用
* @param context
* @param attrs 布局文件参数
*/
public StatusBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
// this(context, attrs, R.style.Base_Theme_AppCompat_Light); // 显示的调用构造方法
}
/**
* 使用默认style 只有明确调用时才生效
* @param context
* @param attrs 布局文件参数
* @param defStyleAttr activity 或 application 的风格
*/
public StatusBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 初始化控件
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusBar);
typedArray.recycle();
init();
}
/**
* 最小 API21 使用 目前没有实际用途
* @param context
* @param attrs
* @param defStyleAttr
* @param defStyleRes
*/
public StatusBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context);
}</span>
首先需要在 res/values/attrs.xml 文件中如下配置:
<declare-styleable name="StatusBar">
<attr name="type" format="string" />
<attr name="greenColor" format="color" />
<attr name="grayColor" format="color" />
<attr name="textGreenColor" format="color" />
<attr name="textGrayColor" format="color" />
<attr name="textSize" format="integer"/>
</declare-styleable></span>
使用 declare-styleable 声明风格,使用attr 来声明具体的参数。
xml中需要使用自定义View的属性,需要声明命名空间,然后直接使用属性:
xmlns:app="http://schemas.android.com/apk/res-auto"
<com.example.administrator.mydemo.widget.StatusBar
android:id="@+id/bar"
app:textSize="14"
app:textGreenColor="#fff000"
android:layout_width="match_parent"
android:layout_height="wrap_content" /></span>
在构造方法代码中接收传递的参数:
public StatusBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 初始化控件
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusBar);
this.textsize = typedArray.getInteger(R.styleable.StatusBar_textSize,14);
this.finishTextColor = typedArray.getColor(R.styleable.StatusBar_textGreenColor,Color.RED);
// 释放资源
typedArray.recycle();
init();
}
通过参数Attributes将传递的参数一一解析,最后不要忘了释放TypeArray资源。
最后跟上这个Demo的GitHub地址:GitHub简单自定义View Demo地址