如何自定义控件

Android开发中,难免会遇到满足不了需求的控件,此时就需要自定来满足。

此处记录一下自定义View的开发过程:

1、开发前在attrs.xml中定义一下属性,自定义属性需要增加format属性,说明此属性是什么格式。

    <declare-styleable name="MyView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>

2、java代码中进行实现

public class MyView extends View {
    private Paint mPaint;
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);//获得所有属性数组;

        //通过TypedArray类的getXXXX()系列接口获得相应的值
        float textSize = array.getDimension(R.styleable.MyView_textSize, 30);
        int textColor = array.getColor(R.styleable.MyView_textColor, 0x990000FF);
        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);
        array.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawRect(new Rect(10, 10, 300, 300), mPaint);
    }
}

3、layout布局中引入,主要是命名空间: xmlns:app="http://schemas.android.com/apk/res/com.dc.test",以及控件引入的属性: app:textColor="#678976"

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res/com.dc.test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <com.hw.test.MyView
        android:id="@+id/myll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:textColor="#678976"
        app:textSize="50sp" />

</RelativeLayout>


这样,一个简单的自定义控件就完成了。[流程]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值