在res\values\ 下新建attrs.xml文件
指定style名字和属性名字以及属性的值类型
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="mViewAttrs">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
属性值:
reference:引用资源ID
color:颜色值
boolean:布尔值
dimension:尺寸值
float:浮点值
integer:整型值
string:字符串
fraction:百分数
enum:枚举值
flag:位或运算
自定义View中引用
package com.ztt.attrs;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View
{
private Paint mPaint;
public MyView(Context context)
{
this(context, null, 0);
}
public MyView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
mPaint = new Paint();
<span style="font-size:24px;"><span style="white-space:pre"> </span>// </span><span style="font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;"><span style="font-size: 13px; line-height: 19.5px;">得到属性集的引用 用 TypedArray的方法取值,参数错误返回默认值</span></span>
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.mViewAttrs, defStyleAttr, 0);
float textSize = a.getDimension(R.styleable.mViewAttrs_textSize, 30);// 防止在XML中没有定义,添加一个默认值 名字_属性
int textColor = a.getColor(R.styleable.mViewAttrs_textColor,0xFFFFFFFF);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
a.recycle();// 一定要调用
// Give back a previously retrieved array, for later re-use.
// 返回之前检索数组,为以后重用。
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);
mPaint.setColor(Color.RED);
canvas.drawText("Hello Attrs", 10, 200, mPaint);
}
}
在XML布局文件中使用自定义View和属性
使用的时候要注意 先声明引用
xmlns:taaaest="http://schemas.android.com/apk/res/com.ztt.attrs"
taaaest:表示引用前缀
com.ztt.attrs:包名
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:taaaest="http://schemas.android.com/apk/res/com.ztt.attrs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<com.ztt.attrs.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
taaaest:textSize="20dp" />
</RelativeLayout>