美文网首页
自定义View学习笔记(一)

自定义View学习笔记(一)

作者: eirunye | 来源:发表于2017-08-25 17:10 被阅读10次

一、自定义控件的绘制原理

请大家先看看这个图:让我们来领略一下自定义view所绘制的流程已经分析经过。

view的绘制是由onMeasure(),onLayout(),onDraw()三个方法来完成的。

自定义view的步骤:

(1)创建一个子View继承View,(2)一般重写子view的三个构造方法,(3)重写onDraw()方法。

自定义属性:

1.在res/valuesl文件夹下创建attrs.xml文件,在该文件下写    ---->这里的name是当我们在布局文件中引用该自定义控件时所需的。

2.在该下自定义属性如:

在format中的属性常用的如下:

分别是:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;

解析:

String:  字符串类型,如上面定义的属性一般是文字信息;

color:   颜色类型,一般是16进制,也可以根据资源文件获取;

demension:是float类型,表示尺寸大小如:上文定义的属性,表示如长宽高等一般单位为sp(文字大小)dp(宽高)

integer:整型数据

enum:枚举类型

reference:资源数据类型,如控件的id、src等

float 是float类型:与demention

flag: 和枚举差不多一样

boolean  : 布尔类型:分别是false和ture

2、定义属性后,接下来是创建改控件的子View,类名就是自定义属性的name=“MyVIew”

如下:

```

public class Myview extends View {

private Paint mPaint;

private int color;

private String textTitle;

private float textSize;

private float dimeWide;

public Myview (Context context) {

this(context, null);

}

public Myview(Context context,AttributeSet attrs) {

this(context,attrs,0);

}

/**

*初始化自定义属性

*@param context

*@param attrs

*@param defStyleAttr

*/

public Myview(Context context,AttributeSet attrs, intdefStyleAttr) {

super(context,attrs,defStyleAttr);

mPaint=new Paint();

TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.MyView,defStyleAttr,0);

color= a.getColor(R.styleable.MyView_color,Color.BLUE);//获取自定义属性由name+“_”+属性名;

textTitle= a.getString(R.styleable.MyView_textTitle);

textSize= a.getDimension(R.styleable.MyView_textSize,20);

dimeWide= a.getDimension(R.styleable.MyView_dimeWide,50);

//或者

/*int n =a.getIndexCount();

for (int i=0;i

int attr = a.getIndex(i);

switch (attr){

case R.styleable.MyView_dimeWide:

dimeWide =a.getDimension(attr,50);

break;

case R.styleable.MyView_color:

color = a.getColor(attr,Color.BLUE);

break;

case R.styleable.MyView_textSize:

// //将typeValue转换为px

textSize = a.getDimension(attr,20);

textSize =a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics()));

break;

case R.styleable.MyView_textTitle:

textTitle = a.getString(attr);

break;

}

}*/

//回收资源

a.recycle();

}

@Override

protected voidon Draw(Canvas canvas) {

super.onDraw(canvas);

//创建画笔

mPaint.setAntiAlias(true);

mPaint.setTextSize(textSize);

mPaint.setStyle(Paint.Style.FILL);

mPaint.setColor(color);

//画圆

canvas.drawCircle(300,300,dimeWide,mPaint);

}}

3、在布局文件中引用该自定义控件

xmlns:app="http://schemas.android.com/apk/res-auto"

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:layout_width="match_parent"

android:layout_height="match_parent"

app:textTitle="我的自定义VIew"

app:textSize="16sp"

app:color="@color/Gray"

/>

相关文章

网友评论

      本文标题:自定义View学习笔记(一)

      本文链接:https://www.haomeiwen.com/subject/flptbttx.html