Android_自定义属性

自定义属性

1 自定义属性的基本步骤

      a 自定义一个CustomView继承View

      b 在valus下编辑 或 创建 attrs.xml例如:


     其中resource是跟标签,可以在里面定义若干个declare-styleable,中name定义了变量的名称,下面可以再自定义多个属性,针对来说,其属        性的名称为"text",format指定了该属性类型为string,只能表示字体的大小。

     format还可以指定其他的类型比如;

     reference   表示引用,参考某一资源ID

    string   表示字符串

    color   表示颜色值

   dimension   表示尺寸值

   boolean   表示布尔值

   integer   表示整型值

   float   表示浮点值

   fraction   表示百分数

   enum   表示枚举值

   flag   表示位运算

c在布局文件中CustomView使用自定义的属性(注意namespace)

d 在CustomView的构造方法中通过TypedArray获取

     TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.test);

     test_mytextview = typedArray.getString(R.styleable.test_mytextview);

    int test_mytest = typedArray.getInteger(R.styleable.test_mytest, -1);

     Log.e("test", "test_mytextview = " + test_mytextview + " , test_mytest = " + test_mytest);

    typedArray.recycle();

2 深入了解自定义属性(AttributeSet)

public MyTextView(Context context, AttributeSet attrs) {

super(context, attrs);

}

构造方法中AttributeSet 也能获取自定义属性的 值  下面方法可以获取出 xml中所有的key value

int attributeCount = attrs.getAttributeCount();

for(int i = 0;i

String attributeName = attrs.getAttributeName(i);

String attributeValue = attrs.getAttributeValue(i);

Log.e("test", "attributeName = " + attributeName + " , attributeValue = " + attributeValue);

}

你可能感兴趣的:(Android_自定义属性)