1、 学习如何自定义控件
开发过程中,为了满足开发需求,实现各种特殊效果,使用android原生控件显得ui很平庸。所以必要的时候要进行自定义控件。
2、自定控件步骤 ——-自定义属性
2.1 创建一个类继承view,实现构造函数,并重写ondraw()方法。
public class MyView extends View {
//代码中直接使用控件会执行这个构造函数
public MyView(Context context) {
super(context);
}
//xml布局中使用控件,设置控件属性执行该构造函数
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
//接受一个style资源执行该构造函数
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
2.2 在res/values目录下创建一个attrs.xml的文件,声明需要自定义的属性,方便在自定义控件中使用属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--声明空间名称-->
<declare-styleable name="MyView">
<!--声明属性名称和类型-->
<attr name="rect_color" format="color"/>
</declare-styleable>
</resources>
2.3 在有两个参数的构造方法中,声明自定义的属性
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
//通过context获取自定义空间,返回TypedArray
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
//获取xml中设置的属性颜色,默认为Color.RED
mColor = typedArray.getColor(R.styleable.MyView_rect_color, Color.RED);
//释放资源
typedArray.recycle();
//设置背景色
this.setBackgroundColor(mColor);
}
}
2.4 在布局文件中使用自定义空间,并设置属性
<com.example.demo.MyView
app:rect_color="#000fff"
android:layout_width="100dp"
android:layout_height="100dp" />
注意: 需要声明命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"
3、 自定义控件 –旋转的方块
3.1 重写自定义空间的ondraw()方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//保存canvas的状态
canvas.save();
//以canvas的中心点旋转
canvas.rotate(degree,canvas.getWidth()/2,canvas.getHeight()/2);
//画出矩形,正方形的开始坐标x 100 y 100 p 画笔
canvas.drawRect(100, 100, 200, 200, p);
//旋转之后重新存储正方形的状态
canvas.restore();
//每次旋转的偏移量
degree++;
//触发view重新绘制,这里需要优化延迟重绘
invalidate();
}
3.2 初始化画笔,在声明的构造函数中初始化画笔
private void initPaint() {
if (p==null){
p=new Paint();
}
p.setColor(Color.BLUE);
}
以上为个人学习笔记,如有错误及不当的地方,请留言,非常感谢。