- 自定义一个CustomView(extends View )类
- 编写values/attrs.xml,在其中编写styleable和item等标签元素
-
<declare-styleable name="CustomView"> <attr name="imgsrc" format="reference"/> <attr name="titleText" format="string"/> <attr name="contentText" format="string"/> </declare-styleable>
- 在布局文件中CustomView使用自定义的属性(注意namespace
xmlns:xxx="http://schemas.android.com/apk/res-auto"
) - 在CustomView的构造方法中通过TypedArray获取
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.CustomView);
String titleText = ta.getString(R.styleable.CustomView_titleText
);
String contentText = ta.getString(R.styleable.CustomViewItems_contentText); int imgsrc = ta.getResourceId(R.styleable.CustomView_imgsrc,0); ta.recycle();