####前言
在android开发过程中,我们不免会遇到一些特殊的情况,有时系统给的ui控件并不能满足我们的开发需求,于是自定义view就显得十分紧迫了,这篇文章就是让大家步入自定义控件的殿堂,让大家了解自定义控件的基本步骤
今天要讲的内容包括:
- 自定义控件的基本步骤
1.1 继承View,并实现它的几个主要构造方法
1.2 重写View的onDraw(Canvas canvas)方法 - 自定义圆圈控件的示例
- 项目结构图和效果图
#####一.自定义控件的基本步骤
######1.1 继承View,并实现它的几个主要构造方法
view有几个重要的构造方法:
View(Context context);
View(Context context, AttributeSet attrs);
View(Context context, AttributeSet attrs, int defStyleAttr);
当然,view的构造方法不只这几个,这里只是重写这几个会用到的。
下面我们以自定义一个CustomerView类来做讲解,CustomerView需要继承view,那么在CustomerView类中就要有这么一句代码:
public class CustomerView extends View{
//中间代码省略
}
然后重写view的几个重要的构造方法,于是于是代码扩充成这样:
public class CustomerView extends View{
public CustomerView(Context context) {
super(context);
}
public CustomerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
######1.2 重写View的onDraw(Canvas canvas)方法
View类的方法有很多,但自定义view的话,基本要重写view的onDraw(Canvas canvas)方法,于是代码继续扩充:
public class CustomerView extends View{
public CustomerView(Context context) {
super(context);
}
public CustomerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//实现你的业务逻辑
//......
}
}
#####二.自定义圆圈控件的示例
在这里,我们写了一个自定义圆圈的控件CustomerView,具体代码在demo有详细解释,这里就不赘述了,下面讲下CustomerView在mainActivity中的引用。
在MainActivity对应的activity_main.xml中引用控件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context="com.android.testdemo.main.MainActivity">
<com.android.testdemo.animation.CustomerView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
#####三.项目结构图和效果图
项目结构图
运行效果图
自定义控件概述
注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权
原文链接:https://blog.csdn.net/findhappy117/article/details/88388668
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
还没有人抢沙发呢~