- 定义 styleable 时,新定义的属性需要包含 format 字段,原有的属性不能包括该字段,例如
<declare-styleable name="ExampleView">
<attr name="maxChar" format="integer"/>
<attr name="android:textSize"/>
</declare-styleable>
- 文字大小或者其他 Dimension 类的属性,在设定时可以按照原有的格式标注 sp, px, dp 等,获取的时候建议统一转换为 px,并通过设定单位的方式来传递给需要的对象。例如设定文字大小,有 styleable:
<declare-styleable name="ExampleView">
<attr name="android:textSize"/>
</declare-styleable>
取值时应该:
TypedArray typedArray = context.obtainStyledAttributes(attributeSet, /*定义的 styleable 文件 ID*/null);
int textSize = attributes.getDimensionPixelSize(R.styleable.ExampleView_android_textSize, 16);
使用时应该:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);