android 自定义view(一)

有的时候Android系统自带的控件并不能满足我们的需求,所以我们就得自己去自定义。
以前看到自定义view都感觉很高大上的样子,感觉技术应该是很牛逼的那种。虽然以前大概了解过自定义view的流程,但是没在工作中用到,也没有深入了解,闲暇之余,还是想多学点东西,毕竟这东西以后能用得到,学习的点点滴滴记录下来,方便以后查找。

一个简单地自定义view。

1.自定义view:首先是写一个类继承view,实现它的构造方法,最少要实现一个构造。

public class CustomView01 extends View{

    public CustomView01(Context context) {
        super(context);
    }
    public CustomView01(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public CustomView01(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

}

2.在values文件下,新建一个自定义属性的xml,名称必须是attrs。定义自定义view的属性,我这里定义了一个String格式的mTxet和一个color格式的mColor。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView01">
        <attr name="mTxet" format="string"/>
        <attr name="mColor" format="color"/>
    </declare-styleable>
</resources>

这样我们就可以在布局文件中使用了。使用我们自己定义的属性,必须在父布局文件里面添加命名空间:“xmlns:app=”http://schemas.android.com/apk/res-auto”,其中的app是一个名称,可以随便定义。

<?xml version="1.0" encoding="utf-8"?>
<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-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.app.lwm.myapplication.MainActivity">

    <com.app.lwm.myapplication.CustomView01
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:mColor="@color/colorAccent"
        app:mTxet="我是自定义的view"
        />
</RelativeLayout>

3.得到自定义属性的值

public CustomView01(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.CustomView01,
                0, 0);
        try {
            mTxet=ta.getString(R.styleable.CustomView01_mTxet);
            mColor=ta.getColor(R.styleable.CustomView01_mColor, Color.BLACK);
        }finally {
            ta.recycle();
        }
    }

4.初始化画笔

private void initPaint(){
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(mColor);
        mPaint.setTextSize(100);
    }

5.在ondraw方法里面画出来

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(mTxet,100, 100, mPaint);
    }

6.效果图
这里写图片描述

源码:https://github.com/lewes1103/customview

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值