Android学习之自定义View

1. 自定义View的一些属性

在第一步,需要我们做的就是在app/res/values下新增一个attrs.xml的文件,这里面申明了View的一些属性,以及我们要使用哪一个类来完成我们自定义View的声明。前面是属性,format是取值类型。

取值类型一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag等类型

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<!-- 这里声明了我们在自定义View时需要用到的的属性>
    <attr name="titleText" format="string" />
    <attr name="titleTextColor" format="color" />
    <attr name="titleTextSize" format="dimension" />
    
    <!-- 这里声明了我们需要在哪一个类中实现自定义View的逻辑>
    <declare-styleable name="CustomTitleView">
        <attr name="titleText" />
        <attr name="titleTextColor" />
        <attr name="titleTextSize" />
    </declare-styleable>

</resources>

2. 定义一个自定义的View类

新建一个包,在这个包的路径下定义一个继承自View的类,然后写三个构造方法。

然后写构造方法的步骤如下:

  1. 通过context获取定义的属性
  2. 遍历这些属性,分别赋值给类中定义的一些成员变量
  3. 回收TypedArray对象(recycle),至于为什么要回收,可以看https://www.jianshu.com/p/33467f64788c这个链接的内容
  4. 通过Paint类的getTextBounds()方法来绘制文本的宽高
public class CustomTitleView extends View {
    // 几个属性
    // 文本内容
    private String mTitleText;
    // 文本颜色
    private int mTitleTextColor;
    // 文本大小
    private int mTitleTextSize;

    //绘制时控制文本绘制的范围以及详细信息
    private Rect mBound;
    private final Paint mPaint;
    // 构造器,主要是传入三个参数那个构造器,传入两个参数的构造器那种
    public CustomTitleView(Context context) {
        this(context,null);
    }

    public CustomTitleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomTitleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取定义的一些属性
        TypedArray styleAttrs = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyleAttr, 0);
        //数一数有多少个属性呢
        int indexCount = styleAttrs.getIndexCount();
        // 循环遍历的方式,找到我们所定义的一些属性
        for (int i=0; i<indexCount; i++){
            //属性的索引值
            int attrIndex = styleAttrs.getIndex(i);
            //根据索引值给java代码中的成员变量赋值
            switch(attrIndex){
                case (R.styleable.CustomTitleView_titleText):
                    mTitleText = styleAttrs.getString(attrIndex);
                    break;
                case (R.styleable.CustomTitleView_titleTextColor):
                    mTitleTextColor = styleAttrs.getColor(attrIndex, Color.GREEN);
                    break;
                case (R.styleable.CustomTitleView_titleTextSize):
                    mTitleTextSize = (int) styleAttrs.getDimension(attrIndex, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics()));
                    break;
            }
        }
        //资源文件中的属性回收
        styleAttrs.recycle();

        // 绘制文本的大小
        mPaint = new Paint();
        mPaint.setTextSize(mTitleTextSize);

        mBound = new Rect();
        // 这个方法主要是一个测量的方法,获取文字环绕的边界
        mPaint.getTextBounds(mTitleText,0,mTitleText.length(),mBound);
   }

3. 重写onMeasure()

在测量规格 MeasureSpec类中,specMode一共有三种:

  • EXACTLY:一般是设置了明确的值或者是MATCH_PARENT
  • AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT
  • UNSPECIFIED:表示子布局想要多大就多大,很少使用、

然后,下面是这次自定义View的代码的展示:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        /*
        MeasureSpec(测量规格)模式分成三类:

        EXACTLY:一般是设置了明确的值或者是MATCH_PARENT

        AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT

        UNSPECIFIED:表示子布局想要多大就多大,很少使用
         */

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        if(widthMode == MeasureSpec.EXACTLY){
            Log.i("customView",widthMode+"");
            width = widthSize;
        } else{
            float textWidth = mBound.width();
            int desiredWidth = (int) (getPaddingLeft() + textWidth + getPaddingRight());
            width = desiredWidth;
        }

        if(heightMode == MeasureSpec.EXACTLY){
            height = heightSize;
        } else{
            float textHeight = mBound.height();
            int desiredHeight = (int) (getPaddingLeft()+ textHeight+ getPaddingRight());
            height = desiredHeight;
        }

        setMeasuredDimension(width,height);
    }

4. 重写onDraw()

测量完成之后就可以通过颜料类Paint,绘制到画布Canvas上。

protected void onDraw(Canvas canvas) {
        mPaint.setColor(Color.YELLOW);
        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),mPaint);
        mPaint.setColor(mTitleTextColor);
        canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);
    }

5. 通过一个Activity来展示效果

创建一个CustomActivity,并且在对应的布局文件中添加自定义组件

public class CustomActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <!-- 命名空间添加这个包的路径,直接用res-auto即可>
    xmlns:custom="http://schemas.android.com/apk/res-auto">

	<!-- 注意到这里的组件应该是我们自定义的View的路径>
    <com.example.customviewdemo.CustomTitleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="20dp"
        custom:titleText="3712"
        custom:titleTextColor="#ff0000"
        custom:titleTextSize="40sp" />

</RelativeLayout>

然后往自定义View的构造器中设置一个监听,通过写一个随机数生成的方法来更新这个view的数字,让其更加多变

// 生成一个随机数
    private String randomText()
    {
        Random random = new Random();
        Set<Integer> set = new HashSet<Integer>();
        while (set.size() < 4)
        {
            int randomInt = random.nextInt(10);
            set.add(randomInt);
        }
        StringBuffer sb = new StringBuffer();
        for (Integer i : set)
        {
            sb.append("" + i);
        }
        return sb.toString();
    }
//添加一个view的事件监听
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mTitleText = randomText();
                postInvalidate();
            }
        });

在这里插入图片描述

6 参考链接

https://blog.csdn.net/lmj623565791/article/details/24252901
https://www.jianshu.com/p/33467f64788c

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值