Android自定义属性

2017-03-07  本文已影响68人  theFullHorizon

自定义属性的流程:

1.根据面向对象的方法分析出自定义View中需要的属性

public class CCircleView extends View {
  private int mbackground;   
  private int mforeground;
  ...
}

2.在values/attrs.xml定义我们的要用到的属性

<declare-styleable name="CustomCircle">
    <attr name="circle_background" format="color"/>
    <attr name="circle_foreground" format="color"/>
    ...
</declare-styleable>

3.在布局文件中使用我们的

<com.nsstudio.customview.cview.CCircleView
    ...
    custom:circle_background="#D4F668"
    custom:circle_foreground="#2F9DD2"
    ... />

4.在自定义View的构造函数中解析

    public CCircleView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomCircle, defStyle, 0);
        for (int i = 0; i < a.getIndexCount(); i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.CustomCircle_circle_background:
                    mbackground = a.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.CustomCircle_circle_foreground:
                    mforeground = a.getColor(attr, Color.BLACK);
                    break;
                ...
            }
        }
        a.recycle();
        ...
     }

分析两个问题

1.自定义控件的构造函数中获取布局文件中属性的方式的种类及其区别:
AttributeSet方式与TypeArray方式,两种方式的区别在于如果布局文件中属性对应的值是引用类型的话,通过AttributeSet方式获取的引用的id,然后需要拿着id去解析。而TypeArray正是帮我们干这个事的。
2.values/attrs.xml中declare-styleable的作用是啥?
从作用角度去分析,首先去掉declare-styleable之后,我们在自定义View的构造函数中拿到TpyedArray,然后需要根据属性在values/attrs.xml定义确定的位置以及资源的Id去拿我们需要的自定义属性值,也就是自定义View类中药定义很多位置整形常量,资源Id的集合。而declare-styleable就是干这个事的。
3.系统中的语义明确的属性我们可以使用吗?
可以,不过values/attrs.xml中属性定义时不需要制定format
values/attrs.xml定义:

<attr name="android:text"/>

布局文件中使用:

android:text = "horizon"

自定义View中获取:

a.getString(R.styleable.CustomSwitch_android_text)

注意的问题

不同开发平台下自定义属性名的定义不一样:
Eclipse : xmlns:custom="http://schemas.android.com/apk/res/自定义控件具体的类地址"
Android Studio : xmlns:custom="http://schemas.android.com/apk/res-auto"
在一个布局文件中使用了不同的自定义View,在Android Studio环境下只需定义一个命名空间即可。

上一篇 下一篇

猜你喜欢

热点阅读