自定义View的自定义属性
1.在 values 文件中,新建attrs.xml 文件(如果原来没有), 内容大致是这样,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--自定义圆角imageview属性-->
<declare-styleable name="RoundImageView">
<attr name="xhradius" format="dimension"></attr>
<attr name="xhtype">
<enum name="fillet" value="0"></enum>
<enum name="round" value="1"></enum>
</attr>
</declare-styleable>
</resources>
解读一下,<declare-styleable name="RoundImageView"> 申明一个控件
,其中 name="RoundImageView" 是定义这个控件的 那个java类的名称.
<attr name="xhradius" format="dimension"></attr> 就是自定义的一条属性,申明了属性的名称和属性的类型。
2.在 自定义View的java类中,使用几个构造方法来接收自定义的值。如
// 半径
private float radius = 0;
// 类型
private int type;
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);//没有这个方法就会出错。没有这句话就会读不到值
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RoundImageView, defStyleAttr, 0);
radius = typedArray.getDimension(R.styleable.RoundImageView_xhradius, 0);//默认半径0
type = typedArray.getInt(R.styleable.RoundImageView_xhtype, 0);//默认圆角类型
typedArray.recycle();
paint=new Paint();
}
3.在布局文件中引用。并设置属性。