这里重温一下自定义View的开发流程,以下将完整的流程走一遍包括自定义属性、onDraw()、等。
继承View类
创建一个类并继承View类,当然如果需求不是很特别的话可以直接继承Android现有的控件拓展开发比如Button等,这些现有的控件类也是继承与View类
继承View类后创建至少一个的构造函数并执行super(context, attrs);
/**
* 有多个构造函数默认需要实现有两个构造参数的构造函数
* @param context 上下文
* @param attrs Xml自定义属性通过这个类传递进来
*/
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
自定义属性
在XML布局中可以使用我们自定义的属性,并通过构造函数传递到类的实体中:
- 在res/values/attrs.xml声明自定义属性
- 在使用到自定义控件的layout中加入自身的命名空间
- 在自定义控件实体类的构造函数中获取属性值
声明自定义属性, name值一般为自定义控件的实体类名
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="isShow" format="boolean" />
<attr name="align" format="enum">
<enum name="left" value="1" />
<enum name="right" value="2" />
</attr>
</declare-styleable>
</resources>
添加命名控件xmlns:app=”http://schemas.android.com/apk/res-auto”
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.xiaoxini2000.customview.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:isShow="true"
app:align="left"
/>
</android.support.constraint.ConstraintLayout>
在实体构造函数中获取属性value 注意:这里TypedArray 因为是共享资源,所以结尾一定要释放
/**
* 有多个构造函数默认需要实现有两个构造参数的构造函数
* @param context 上下文
* @param attrs Xml自定义属性通过这个类传递进来
*/
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = null;
try {
typedArray = context.getTheme().obtainStyledAttributes(attrs,R.styleable.CustomView,0,0);
isShow = typedArray.getBoolean(R.styleable.CustomView_isShow,false);
align = typedArray.getIndex(R.styleable.CustomView_align);
}finally {
typedArray.recycle();
}
}