前言:学了两天自定义View兴致比较高,之前学习都比较片面,这几天学习的比较系统,也明白了很多东西例如自定义View的整体流程,自定义View要是用的一些类 ,比如Paint呀,TypedArray呀,MeasureSpec等等,都有了个初步了解,后续我也会在工作中通过文档补充更详细的知识点,为了巩固知识,就做了个闲鱼底部的菜单栏,突然就发现这种菜单栏也是越来越流行了呀,就做了一个,下面就是整体流程。
开源链接 : https://github.com/Nixo0427/NixoBottomButton
效果图:
本文整体分位4个部分去说这个控件,最后会放出自定义控件类的整体代码
一、在attrs里声明需要的属性
二、获取属性值
三、测量大小
四、绘制
一、声明属性
首先在values里创建一个attrs.xml(名字可以随意起)
然后再里面去声明自己想要使用的属性,首先我们需要对比图片分析一下这个控件需要哪些值,思考过后,我们得出大概会的出控件大概会有以下属性
1.背景
2.文本
3.文本大小
4.圆距离底部的距离
5.圆的边框
6.圆的边框颜色
7.圆的颜色
8.圆的半径
那么我们就在里面声明这8个属性
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="NixoBottomButton"> <attr name="android:background"/> <attr name="android:text"/> <attr name="textSize" format="integer"/> <attr name="isClick" format="boolean"/> <attr name="circlePaddingBottom" format="integer"/> <attr name="circleFrame" format="integer"/> <attr name="circleFrameColor" format="color"/> <attr name="circleColor" format="color"/> <attr name="circleRadis" format="integer"/> </declare-styleable> </resources>
这样我们第一步就完成了
二、获取属性值
我们定义好属性,我们就需要获取值方便做后面的操作,比如绘制,我们新建一个类并继承Button
接下来声明一个TyedArray去获取属性,代码如下
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.NixoBottomButton); mTextSize = (int)typedArray.getFloat(R.styleable.NixoBottomButton_textSize,30); // mText = typedArray.getString(R.styleable.NixoBottomButton_android_text); mIsClick = typedArray.getBoolean(R.styleable.NixoBottomButton_isClick,false); mCircleColor = typedArray.getColor(R.styleable.NixoBottomButton_circleColor, Color.parseColor("#a3cf62")); mBackground = typedArray.getColor(R.styleable.NixoBottomButton_android_background, Color.parseColor("#00000000")); mPaddingBottom = typedArray.getInt(R.styleable.NixoBottomButton_circlePaddingBottom,20); mRaids = typedArray.getInt(R.styleable.NixoProgessBar_CircleRaids,0); mCircleFrameColor = typedArray.getColor(R.styleable.NixoBottomButton_circleFrameColor,Color.WHITE); mCircleFrame = typedArray.getInt(R.styleable.NixoBottomButton_circleFrame,5); mPlusAnimator = AnimatorInflater.loadAnimator(context,R.animator.plus_animator); typedArray.recycle();
最后不要忘记使用.recycle()方法进行回收,可能有的朋友发现了,圆的中心是有个加号的,这个属性并没有声明,的确是这样,但是不要紧,我们可以对外暴露个方法,让用户设置这个Icon,所以我们声明个int型的mIcon,然后通过如下代码转换成Bitmap
public void setIcon(int icon){ mIcon = icon; } public int getIcon(){ return mIcon; }
plus = ((BitmapDrawable) getContext().getResources().getDrawable(mIcon)).getBitmap();
这样,我们的属性获取就算告一段落了。
三、测量大小
测量大小是模板的写法,我们复写onMeasure方法,通过他给我们的widthMeasureSpec和heightMeasureSpec进行我们的模式对比,去设置不同的大小
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int SpecWidth = MeasureSpec.getSize(