一、自定義控件的繪制原理
請大家先看看這個圖:讓我們來領略一下自定義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"
/>