初学android时,会的仅仅是将控件互相组合形成新的控件,当然这也属于自定义控件的一种。但这仅仅是初级的,现在小编要成长起来,自己绘制自定义view。
先建立一个viewclass,如以下代码:
public class CustomizeView extends View {
public CustomizeView(Context context) {
super(context);
}
public CustomizeView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomizeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
这是一个自定义view,其中的3个属性context,attrs,defStyleAttr分别代表的是引用的上下文,属性,系统中或者自定义的一个主题。这些都是自定义view的一个参数设置问题。
然后在布局中使用,如以下代码:
<?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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.lgb.customizeview1.MainActivity">
<com.example.lgb.customizeview1.CustomizeView
android:layout_centerInParent="true"
android:id="@+id/customview1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
当然这样运行,界面还是一片空白,我们要往view中添加点东西!首先我们要重写onDraw这个方法,这个方法是绘制view的关键。这里我们要提一下,在android中绘制图形与现实中绘画有点相似,都具有基本元素画笔和画布2样东西--paint,canvas!如以下代码
<pre name="code" class="java"> /**
* 初始化画笔
* 在ondraw中不建议初始化画笔,因为draw是一个不断重复执行的方法,在里面最好不要执行耗时耗内存的
* 操作,一个会造成内存暴涨,app会卡死甚至造成ANR!
*/
private void initPaint(){
mPaint = new Paint();
//透明度
mPaint.setAlpha(80);
//抗锯齿
mPaint.setAntiAlias(true);
//画笔颜色
mPaint.setColor(Color.BLACK);
//.....
当然android是个智能的语言,肯定带有一些常用的图形,如圆形之类的,如下代码:
<pre name="code" class="java"> @Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画一个圆
canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, 200, mPaint);
}
运行结果
<img src="https://img-blog.csdn.net/20161012133108132?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
看这就是我们画出来的第一个自定义view(虽然有点low,只有个圆。。。。)