android 自定义View属性
玩android上层应用很多年了。对很多东西一直不透彻,可怎么整,人生的路该怎么走。干啥都不容易。得尝试学习下View的属性设置。这里我还不能介绍如何写View,只是说下如何设置View的属性。
public class MyView extends View {
private Paint mPaint;
private Context mContext;
public MyView(Context context,AttributeSet attrs)
{
super(context,attrs);
mPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_textColor,
0XFFFFFFFF);
float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
a.recycle();
}
所有的View都这样写,关键研究下这些xml的关系。首先我们在整个layout里会有这样的东西
<com.example.test.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="20px"
test:textColor="#fff"/>
这个就比较诡异了。第一句声明了那个View. 勉强可以接受,关键这两句
test:textSize="20px"
test:textColor="#fff"/>
为什么要这样写呢,我这样行不行 qisda:changer = "20px" 肯定不行,那这个test:textSize是谁定义的呢?
这需要我们在写个文件,知名自定义View有哪些属性,在attrs.xml里
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
奥,哪就有些明白了,哪这样,我在这个文件里,我再加个声明
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
<declare-styleable name="View">
<attr name="changer1_color" format="color" />
<attr name="changer2_size" format="dimension" />
</declare-styleable>
</resources>
那我的xml layout属性是否可以写成
<com.example.test.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="20px"
test:changer1_color="#fff"
test:changer2_size="20px"
test:textColor="#fff"/>
哎,开发环境没拨错,好。原来是可以的。那这不乱套了,诡异,原来问题出在这里。
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyView);
这句话的意思,attrs读了layout xml用户的设定值,都包含进来了,R.styleable,myView指定了该View关心或者可以设定哪些值。 这个意思就是虽然你多设定了一些属性值,但是我读取也没用的。相当于系统从style里读键,从attrs找键对应的值,统一整理存放到Typearray里。
哎,android博大精深,可怎么整,要不要换个工作呢。