您的位置:首页 > 其它

关于自定义view的一些问题

2017-01-19 19:01 232 查看
最近遇到了较为棘手的重写view的问题。首先是写构造方法。按照原生的写法是单参数构造方法调用自己的双参数构造方法,双参数构造方法调用自己的三个参数的构造方法,而不能使用像编译器推荐的那样只调用父类的构造方法。按照原生view的写法初始化只需在三个参数的构造方法中完成即可,而不用每个构造方法都写一遍。

关于属性的声明。我们可以在attrs.xml中定义一些我们需要的属性,用<attr>定义。如果集中起来可以形成一个<declare-styleable>,这个同样放在attr.xml中。若需要在layout的xml中引用,则需要声明

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:erone="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

后面即可用erone:xxxx=""来使用属性了。

关于属性的读取。参照源码,我们可以如下写

final Resources.Theme theme = context.getTheme();
TypedArray a = theme.obtainStyledAttributes(
attrs, R.styleable.Erone, defStyleAttr, 0);

int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case xxx:
int c=a.getColor(attr,0);
break;

case xxx1:
float d=a.getDimension(attr,0);
break;

}
}
a.recycle();

其中R.styleable.Erone是我在attr定义的一个<declare-styleable>属性集合的名字,代表你要寻找在这底下被定义的属性,switch判断属性id后即可拿到对应的值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: