转载请标明出处:https://blog.youkuaiyun.com/ZhijunHong/article/details/108511627,谢谢~
写在前面
如果你一直在苦恼产品经理总是抱怨“为什么苹果可以做,Android就不可以balabala…",如果你希望理直气壮的对设计狮来一句”不要问我能不能做,我只想知道你想不想要…"
Android自定义View是每一个Android开发者成为高级开发工程师的必经之路,今天我们就来以继承View的方式实现一个简单的加载进度条,讲解Android自定义View的步骤。
奉上产送门:https://github.com/zhijunhong/custom_view/tree/master/number_prograss
一、继承android.view.View,重写构造方法
-
新建项目工程后,右击新建LineProgress类并继承android.view.View,编译器会提示强制重写构造方法,一般会重写以下三个构造方法
public LineProgress(Context context) { this(context, null); } public LineProgress(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public LineProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); .... }
规则就是第一个构造调用第二个构造,第二个构造调用第三个构造,在第三个构造里面做变量和画笔的初始化操作。
二、自定义属性和获取属性值
- 步骤1中第三个构造方法里面参数AttributeSet attrs指的是用户自定义属性,所以在此之前我们需要自定义View的属性。简单想一下一个简单进度条大概有的属性就是:
-
进度条最大长度值、当前长度值;
-
已到达部分的长度和颜色;
-
未到达部分的长度和颜色;
-
进度文本是否显示,文本的颜色和大小
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LineProgress">
<attr name="progress_max" format="integer" />
<attr name="progress_current" format="integer" />
<attr name="progress_unreached_color" format="color" />
<attr name="progress_research_color" format="color" />
<attr name="progress_unreached_bar_height" format="dimension" />
<attr name="progress_research_bar_height" format="dimension" />
<attr name="progress_text_color" format="color" />
<attr name="progress_text_size" format="dimension" />
<attr name="progress_text_offset" format="dimension" />
<attr name="progress_text_visibility" format="enum">
<enum name