自定义View-自定义属性如:app:circle_color ="@color/colorPrimary"

先在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  后面是跟的包名
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值