android 自定义属性

public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.tt);
        boolean aBoolean = typedArray.getBoolean(R.styleable.tt_current, true);
        int anInt = typedArray.getInt(R.styleable.tt_future, -1);
        System.out.println(aBoolean+":"+anInt);
    }
  • AttributeSet保存的是在布局里面设置的属性,但是无法拿到引用
  • typedArray可以拿到指定的属性
    <declare-styleable name="tt">
        <attr name="current" format="boolean"/>
        <attr name="future" format="integer"/>
    </declare-styleable>
    <attr name="attr1" format="color"/>
  • <declare-styleable>用来指定属性集,属性也可以单独设置,名字可以任意设置
  1. 要为自定义View自定义属性,可以通过declare-styleable声明需要的属性
  2. 为了在Theme设置View的默认样式,可以同时定义一个format为reference的属性att_a, 定义Theme时为这个attribute指定一个Style,并且在View的第二个构造函数中将R.attr.attr_a 作为第三个参数调用第三个构造函数
  3. 可以定义一个Style作为Theme中没有定义attr_a时View属性的默认值。
  4. 可以在Theme中直接为属性赋值,但优先级最低
  5. 当defStyleAttr(即View的构造函数的第三个参数)不为0且在Theme中有为这个attr赋值时,defStyleRes(通过obtainStyledAttributes的第四个参数指定)不起作用
  6. 属性值定义的优先级:xml>style>Theme中的默认Sytle>默认Style(通过obtainStyledAttributes的第四个参数指定)>在Theme中直接指定属性值
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容