如何定制自己的View
关于如何定制自己的View,查了相关的文档也看了一些例子,现在把自己的理解总结一下,和大家分享。
制定自己的View,一般要继承自某一类的View,然后完成构造方法,以及对onDraw()的重写,构造方法里面涉及到一些自定义的属性,自定义的属性在res/values下新建一个attrs.xml中申明,如下所示:
arrts.xml<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="MyView" > <attr name="text_color" format="color" /> <attr name="text_size" format="dimension" /> </declare-styleable ></resources>
package com.lee.view;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.util.AttributeSet;import android.view.View;public class MyView extends View {private Paint myPaint;//画笔private static final String BLOG = "http://xueyilee.iteye.com";public MyView(Context context) {super(context);myPaint = new Paint();}/*Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.xml布局文件有该View时就调用此构造方法,属性会传给attrs*/public MyView(Context context, AttributeSet attrs) {super(context, attrs);myPaint = new Paint();//获得TypedArray接口容器,通过它可以检索自定义的属性TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyView);//检索属性值,第二个参数是默认值,如果没有定义则返回默认值int textColor = ta.getColor(R.styleable.MyView_text_color, 0xff0000);float textSize = ta.getDimension(R.styleable.MyView_text_size, 30);myPaint.setColor(textColor);myPaint.setTextSize(textSize);ta.recycle();//这个回收方法一定不要忘了}/*当View渲染它的内容的时候调用此方法*/@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);myPaint.setStyle(Style.FILL);//设置填充myPaint.setAntiAlias(true);//消除锯齿canvas.drawCircle(50, 50, 30, myPaint);myPaint.setColor(Color.BLUE);canvas.drawText(BLOG, 20, 100, myPaint);}}main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" //这个命名空间部分千万不要忘了,它是自定义属性前缀xmlns:lee="http://schemas.android.com/apk/res/com.lee.view"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent" ><com.lee.view.MyViewandroid:layout_width="match_parent"android:layout_height="wrap_content"lee:text_color="#00ff00"lee:text_size="20px"/></LinearLayout>
