Skip to content

Instantly share code, notes, and snippets.

@twiceyuan
Last active October 29, 2018 06:26
Show Gist options
  • Save twiceyuan/126c2313fe4e9048160a to your computer and use it in GitHub Desktop.
Save twiceyuan/126c2313fe4e9048160a to your computer and use it in GitHub Desktop.
[自定义 View 的属性传递注意项] Android custom view deliver variable tips #Android
  1. 定义 styleable 时,新定义的属性需要包含 format 字段,原有的属性不能包括该字段,例如
<declare-styleable name="ExampleView">
  <attr name="maxChar" format="integer"/>
  <attr name="android:textSize"/>
</declare-styleable>
  1. 文字大小或者其他 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment