Android的UI都是基于View 和 ViewGroup的, 所以如果我们要自定义视图组件就要基于View类.
这个示例的工程结构图
一 添加一个类
TestView类继承于View
实现两个构造方法
//com.ex.TestView
TestView源码package com.ex; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class TestView extends View { private Paint mPaint = null; private Context mContext = null; /** * mTestView = new TestView(this); setContentView(mTestView); * 如果在Activity中这样写,那么就需要实现这个构造函数 */ public TestView(Context context) { super(context); mContext = context; mPaint = new Paint(); } /** * setContentView(R.layout.main); mTestView = * (TestView)findViewById(R.id.mTestView); 如果在Activity中这样写,那么就需要实现这个构造函数 */ public TestView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mPaint = new Paint(); TypedArray params = context.obtainStyledAttributes(attrs, R.styleable.TestView); // 取得xml布局文件中所定义的背景 int backgroudId = params.getResourceId(R.styleable.TestView_backGround, 0); if (backgroudId != 0) { setBackgroundResource(backgroudId); } // 字体颜色 int textColor = params.getColor(R.styleable.TestView_textColor, 0XFFFFFFFF); mPaint.setColor(textColor); // 字体大小 float textSize = params.getDimension(R.styleable.TestView_textSize, 20); mPaint.setTextSize(textSize); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 测试绘制一个矩形 canvas.drawRect(30, 50, 80, 90, mPaint); // 绘制一个字符串 canvas.drawText("测试字符串", 50, 150, mPaint); } }
二 声明属性值
/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<declare-styleable name="TestView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
<attr name="backGround" format="integer" />
</declare-styleable>
</resources>
三 使用示例
/res/layout/main.xml xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:test="http://schemas.android.com/apk/res/com.ex" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <com.ex.TestView android:id="@+id/mTestView" test:textColor="#FFFFFFFF" test:textSize="25dip" android:layout_height="wrap_content" android:layout_width="wrap_content" /> LinearLayout>