自定义控件(二)

上一章,我们讲了一个最基本的View的绘制,并且举了一个简单的栗子。

那我们就继续深入下去:

在现实的项目中,大家肯定会遇到很多的圆,圆里也有很多的文字!字和圆的颜色都不一样。难道我们每一个要自定义一下吗?

当然不需要!解决方案就是自定义属性!通过自定义属性来对字的颜色,和圆的颜色进行设置。

那么怎么自定义属性呢?

打开Values文件夹下的attrs.xml文件,定义以下属性:

<declare-styleable name="CommonCircleView">
    <attr name="cirpaintColor" format="color" />
    <attr name="cirtextColor" format="color" />
    <attr name="cirisFill" format="boolean" />
    <attr name="cirtext" format="string" />
    <attr name="cirtextSize" format="dimension" />
</declare-styleable>
然后再自定义View的构造方法中,读取自定义的属性的值

private void initType(Context context, AttributeSet attrs) {
    // 读取attrs里面的属性
    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.CommonCircleView);
    int n = a.getIndexCount();
    for (int i = 0; i < n; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
            case R.styleable.CommonCircleView_cirpaintColor:
                mPaintColor = a.getColor(attr, 0x45C01A);
                break;

            case R.styleable.CommonCircleView_cirisFill:
                mIsFill = a.getBoolean(attr, false);
                break;

            case R.styleable.CommonCircleView_cirtextColor:
                mTextColor = a.getColor(attr, 0x45C01A);
                break;

            case R.styleable.CommonCircleView_cirtext:
                mText = a.getString(attr);
                break;

            case R.styleable.CommonCircleView_cirtextSize:
                mTextSize = (int) a.getDimension(attr, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10,
                        getResources().getDisplayMetrics()));
                break;
        }
    }
    a.recycle();
    //自定义字体
    typeface = Typeface.createFromAsset(getResources().getAssets(), "IMPACT_1.TTF");
}

然后就是简单的画圆和写文字啦!


下载链接:http://download.csdn.net/detail/qq_29375071/9380529

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值