先在value下创建类似于attrs.xml的文件
<resources>
<declare-styleable name="CircleView">
<attr name="circle_color" format="color"/>
<attr name="aa" format="reference"/><!--指的是资源id-->
<attr name="size" format="dimension"/><!--指的是尺寸-->
</declare-styleable>
</resources>
然后在自定义View中:
private int mColor = Color.BLACK;
public DxView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
a.recycle();//垃圾回收。一般是系统自动回收,但是有时候系统可能不是马上回收,
paint.setColor(mColor);
}
布局文件:
<com.kaili.www.test_listview.view.DxView
android:background="@android:color/holo_red_dark"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="20dp"
app:circle_color ="@color/colorPrimary"
android:padding="20dp"/>
如果添加了这一句:app:circle_color ="@color/colorPrimary" 那么mColor的颜色就是它,如果没有添加这一句,就是默认颜色Color.RED
需要注意的是上面还有这个xmlns:app="http://schemas.android.com/apk/res-auto" 申明它,app才知道去那里,也可以写成xmlns:app="http://schemas.android.com/apk/res/com.kaili.www.test_listview 后面是跟的包名