1.values 文件夹下,新建attrs.xml,在resource节点下写:
<declare-styleable name="FillInInfoView"> <attr name="pic" format="reference"/> <attr name="etHint" format="string"/> </declare-styleable>
2.在自定义view里面获取自定义属性
第一种方式:
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.FillInInfoView); Drawable drawable = ta.getDrawable(R.styleable.FillInInfoView_pic); String string = ta.getString(R.styleable.FillInInfoView_etHint); ta.recycle();
第二种方式:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CircleView, defStyleAttr, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int arr = a.getIndex(i); switch (arr) { case R.styleable.CircleView_innerCircleColor: innerColor = a.getColor(arr, Color.BLUE); break; case R.styleable.CircleView_innerCircleSize: innerCircleSize = a.getDimensionPixelSize(arr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); break; case R.styleable.CircleView_outCircleSize: outCircleSize = a.getDimensionPixelSize(arr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); break; case R.styleable.CircleView_smallCircleSize: outSmallCircleSize = a.getDimensionPixelSize(arr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); break; case R.styleable.CircleView_smallCircleRadiousSize: outSmallCircleRadiousSize = a.getDimensionPixelSize(arr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); break; } } a.recycle();