1.编写attrs属性文件。android在默认情况下并没有attrs.xml,我们需要手动在values目录下新建一个这样的文件。文件根结点是resources,子节点叫declare-styleable,比如下面就是一个attrs文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myview">
<attr name="radius" format="integer"></attr>
<attr name="color" format="color"></attr>
</declare-styleable>
</resources>package com.example.attributedemo;
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 mPaint = null;
/**
* 圆颜色
*/
private int mColor;
/**
* 圆半径
*/
private int mRadius;
/**
* 默认颜色
*/
private static final int DEFAULT_COLOR = Color.RED;
/**
* 默认半径
*/
private static final int DEFAULT_RADIUS = 50;
public MyView(Context context)
{
super(context);
mColor = DEFAULT_COLOR;
mRadius = DEFAULT_RADIUS;
init();
}
public MyView(Context context, AttributeSet attrs)
{
super(context, attrs, 0);
getConfig(context, attrs);
init();
}
/**
* 初始化画笔
*/
private void init()
{
mPaint = new Paint();
mPaint.setStrokeWidth(1);
mPaint.setStyle(Style.FILL);
mPaint.setColor(mColor);
}
/**
* 从xml中获取配置信息
*/
private void getConfig(Context context,AttributeSet attrs)
{
//TypedArray是一个数组容器用于存放属性值
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.myview);
mRadius = ta.getInt(R.styleable.myview_radius, DEFAULT_RADIUS);
mColor = ta.getColor(R.styleable.myview_color, DEFAULT_COLOR);
//用完务必回收容器
ta.recycle();
}
@Override
protected void onDraw(Canvas canvas)
{
//画一个圆
canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);
}
}RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myview="http://schemas.android.com/apk/res/com.example.attributedemo"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.attributedemo.MyView
android:layout_width="200dp"
android:layout_height="200dp"
myview:radius="40"
myview:color="#bc9300" />
</RelativeLayout>【安卓笔记】带自定义属性的view控件,布布扣,bubuko.com
原文:http://blog.csdn.net/chdjj/article/details/38417893