在自定义View时,我们通常会去重写onDraw()方法来绘制View的显示内容。如果该View还需要使用wrap_content属性,那么还必须重写onMeasure()方法。另外,通过自定义attrs属性,还可以设置新的属性配置值。
在View中通常有一些比较重要的回调方法。
- onFinishInflate():从XML加载组件后回调。
- onSizeChanged(;:组件大小改变时。
- onMeasure():回调该方法来进行测量。
- onLayout():回调该方法来确定显示的位置。
- onTouchEvent():监听到触摸事件时回调。
当然,创建自定义View的时候,并不需要重写所有的方法,只需要重写特定条件的回调方法即可。这也是Android控件架构灵活性的体现。
通常情况下,有以下三种方法来实现自定义的控件。
- 对现有控件进行拓展
- 通过组合来实现新的控件
- 重写View来实现全新的控件
对现有控件进行拓展
这是一个非常重要的自定义View方法,它可以在原生控件的基础上进行拓展,增加新的功能、修改显示的UI等。一般来说,我们可以在onDraw()方法中对原生控件行为进行拓展。
比如想让一个TextView的背景更加丰富,给其多绘制几层背景,如下图所示:
代码如下:
public class MyTextView extends TextView {
private Paint mPaint1;
private Paint mPaint2;
public MyTextView(Context context) {
super(context);
initView(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
initView(context);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context) {
// 初始化画笔
mPaint1 = new Paint();
// mPaint1.setColor(getResources().getColor(android.R.color.holo_blue_light)); //getColor已过时
mPaint1.setColor(ContextCompat.getColor(context, android.R.color.holo_blue_light));
mPaint1.setStyle(Paint.Style.FILL);
mPaint2 = new Paint();
mPaint2.setColor(Color.YELLOW);
mPaint2.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
//在回调父类方法前,实现自己的逻辑,对TextView来说即是在绘制文本内容前
//绘制外层矩形
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint1);
//绘制内层矩形
canvas.drawRect(10, 10, getMeasuredWidth() - 10, getMeasuredHeight() - 10, mPaint2);
canvas.save();
//绘制文字前平移10像素
canvas.translate(10, 0);
//父类完成的方法,即绘制文本
super.onDraw(canvas);
canvas.restore();
//在回调父类方法后,实现自己的逻辑,对TextView来说即是在绘制文本内容后
}
}
下面再来一个利用LinearGradient Shader和Matrix实现的一个动态的文字闪动效果,效果如下:
要想实现这一个效果,可以充分利用Android中Paint对象的Shader渲染器。通过设置一个不断变化的LinearGradient,并使用带有该属性的Paint对象来绘制要显示的文字。
代码如下:
public class ShineTextView extends TextView {
private static final String TAG = ShineTextView.class.getSimpleName();
//线性渐变渲染
private LinearGradient mLinearGradient;
//渲染矩阵
private Matrix mGradientMatrix;
//画笔
private Paint mPaint;
private int mViewWidth = 0;
// 亮度位移距离
private int mTranslate = 0;
public ShineTextView(Context context) {
super(context);
}
public ShineTextView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public ShineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mViewWidth == 0) {
mViewWidth = getMeasuredWidth();
if (mViewWidth > 0) {
//获取当前绘制TextView的Paint对象
mPaint = getPaint();
// 创建LinearGradient对象
// 起始点坐标(-mViewWidth, 0) 终点坐标(0,0)
// 第一个,第二个参数表示渐变起点 可以设置起点终点在对角等任意位置
// 第三个,第四个参数表示渐变终点
// 第五个参数表示渐变颜色
// 第六个参数可以为空,表示坐标,值为0-1
// 如果这是空的,颜色均匀分布,沿梯度线。
// 第七个表示平铺方式
// CLAMP重复最后一个颜色至最后
// MIRROR重复着色的图像水平或垂直方向已镜像方式填充会有翻转效果
// REPEAT重复着色的图像水平或垂直方向
mLinearGradient = new LinearGradient(-mViewWidth, 0, 0, 0, new int[]{
Color.BLUE, 0xffffffff, Color.BLUE}, null, Shader.TileMode.CLAMP);
//设置原生TextView没有的LinearGradient属性
mPaint.setShader(mLinearGradient);
mGradientMatrix = new Matrix();
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mGradientMatrix != null) {
//在该方法中,通过矩阵的方式不断平移渐变效果,从而在绘制文字时,产生动态的闪动效果
mTranslate += mViewWidth / 10;
if (mTranslate > 2 * mViewWidth) {
mTranslate = 0;
}
mGradientMatrix.setTranslate(mTranslate, 0);
mLinearGradient.setLocalMatrix(mGradientMatrix);
//100毫秒重绘一次
postInvalidateDelayed(100);
}
}
}
创建复合控件
创建复合控件可以很好的创建出具有重用功能的控件集合。这种方式通常需要继承一个合适的ViewGroup,再给它添加指定功能的控件,从而组合成新的复合控件。通过这种方式创建的控件,我们一般会给它指定一些可配置的属性,让其具有更强的拓展性。下面以一个TopBar的为例
该如何创建一个这样的公共UI模板。首先,模板应该具有通用性与可定制性。也就是说,我们需要给调用者以丰富的接口,让他们可以更该模板中的文字、颜色、行为等信息,而不是所有的模板都一样,那样就失去了模板的意义。
定义属性
为一个View提供可自定义的属性非常简单,只需要在res资源目录的values目录下创建一个attrs.xml的属性定义文件,并在该文件中定义相应的属性即可。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--有些属性可以是颜色属性,也可以是引用属性。
比如按钮的背景,可以把它指定为具体的颜色,也可以把它指定为
一张图片,所以用“|”来分隔不同的属性——reference|color-->
<declare-styleable name="TitleBar">
<attr name="title" format="string" />
<attr name="titleTextSize" format="dimension" />
<attr name="titleTextColor" format="color" />
<attr name="leftTextColor" format="color" />
<attr name="leftImageDrawable" format="reference|color" />
<attr name="leftText" format="string" />
<attr name="rightTextColor" format="color" />
<attr name="rightImageDrawable" format="reference|color" />
<attr name="rightText" format="string" />
</declare-styleable>
</resources>
组合控件
UI模板TopBar实际上由三个控件组成,即左边的点击按钮mLeftButton,右边的点击按钮mRightButton和中间的标题栏mTitleView。通过动态添加控件的方式,使用addView()方法将这三个控件加入到定义的TopBar模板中,并给它们设置我们获取到的具体的属性值,代码如下。
public class TitleBar extends RelativeLayout {
// 包含TitleBar上的元素:左按钮、右按钮、标题
private ImageButton mLeftButton, mRightButton;
private TextView mTitleView;
// 布局属性,用来控制组件元素在ViewGroup中的位置
private LayoutParams mLeftParams, mTitleParams, mRightParams;
// 左按钮的属性值,即我们在attrs.xml文件中定义的属性
private int mLeftTextColor;
private Drawable mLeftImageDrawable;
private Drawable mRightImageDrawable;
private String mLeftText;
// 右按钮的属性值,即我们在atts.xml文件中定义的属性
private int mRightTextColor;
private Drawable mRightBackground;
private String mRightText;
// 标题的属性值,即我们在atts.xml文件中定义的属性
private float mTitleTextSize;
private int mTitleTextColor;
private String mTitle;
// 映射传入的接口对象
private titleBarLeftClickListener mLeftClickListener;
private titleBarRightClickListener mRightClickListener;
public TitleBar(Context context) {
this(context, null);
}
public TitleBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttrs(context, attrs);
initView(context);
}
private void initAttrs(Context context, AttributeSet attrs) {
// 通过这个方法,将你在attrs.xml中定义的declare-styleable的所有属性的值存储到TypedArray中
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TitleBar);
// 从TypedArray中取出对应的值来为要设置的属性赋值
mLeftTextColor = ta.getColor(R.styleable.TitleBar_leftTextColor, 0);
mLeftImageDrawable = ta.getDrawable(R.styleable.TitleBar_leftImageDrawable);
mLeftText = ta.getString(R.styleable.TitleBar_leftText);
mRightTextColor = ta.getColor(R.styleable.TitleBar_rightTextColor, 0);
mRightImageDrawable = ta.getDrawable(R.styleable.TitleBar_rightImageDrawable);
mRightText = ta.getString(R.styleable.TitleBar_rightText);
mTitleTextSize = ta.getDimension(R.styleable.TitleBar_titleTextSize, 10);
mTitleTextColor = ta.getColor(R.styleable.TitleBar_titleTextColor, 0);
mTitle = ta.getString(R.styleable.TitleBar_title);
// 获取完TypedArray的值后,一般要调用recycle方法用来避免重新创建的时候的错误
ta.recycle();
}
private void initView(Context context) {
mLeftButton = new ImageButton(context);
mRightButton = new ImageButton(context);
mTitleView = new TextView(context);
//为创建的组件元素赋值
//值就来源于我们在引用的xml文件中给对应属性的赋值
// mLeftButton.setTextColor(mLeftTextColor);
mLeftButton.setImageDrawable(mLeftImageDrawable);
mLeftButton.setBackgroundResource(android.R.color.transparent);
// mLeftButton.setText(mLeftText);
// mRightButton.setTextColor(mRightTextColor);
mRightButton.setImageDrawable(mRightImageDrawable);
mRightButton.setBackgroundResource(android.R.color.transparent);
// mRightButton.setText(mRightText);
mTitleView.setText(mTitle);
mTitleView.setTextColor(mTitleTextColor);
mTitleView.setTextSize(mTitleTextSize);
mTitleView.setGravity(Gravity.CENTER);
//为组件元素设置相应的布局元素
mLeftParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mLeftParams.addRule(RelativeLayout.ALIGN_PARENT_START, TRUE);
} else {
mLeftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
}
//添加到ViewGroup
addView(mLeftButton, mLeftParams);
mRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mRightParams.addRule(RelativeLayout.ALIGN_PARENT_END, TRUE);
} else {
mRightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
}
addView(mRightButton, mRightParams);
mTitleParams = new LayoutParams(LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
mTitleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
addView(mTitleView, mTitleParams);
// 按钮的点击事件,不需要具体的实现,
// 只需调用接口的方法,回调的时候,会有具体的实现
mLeftButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mLeftClickListener != null) {
mLeftClickListener.leftClick();
}
}
});
mRightButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mRightClickListener != null) {
mRightClickListener.rightClick();
}
}
});
}
public void setTitle(String mTitle) {
if (mTitleView != null) {
this.mTitle = mTitle;
mTitleView.setText(mTitle);
}
}
public void setLeftButtonVisible(boolean flag) {
if (mLeftButton != null) {
if (flag) {
mLeftButton.setVisibility(View.VISIBLE);
} else {
mLeftButton.setVisibility(View.GONE);
}
}
}
public void setRightButtonVisible(boolean flag) {
if (mRightButton != null) {
if (flag) {
mRightButton.setVisibility(View.VISIBLE);
} else {
mRightButton.setVisibility(View.GONE);
}
}
}
public void setOnTitleBarLeftClickListener(titleBarLeftClickListener mLeftClickListener) {
this.mLeftClickListener = mLeftClickListener;
}
public void setOnTitleBarRightClickListener(titleBarRightClickListener mRightClickListener) {
this.mRightClickListener = mRightClickListener;
}
// 接口对象,实现回调机制,在回调方法中
// 通过映射的接口对象调用接口中的方法
// 而不用去考虑如何实现,具体的实现由调用者去创建
public interface titleBarLeftClickListener {
//左按钮点击事件
void leftClick();
}
public interface titleBarRightClickListener {
//右按钮点击事件
void rightClick();
}
}
引用UI模板
如果要使用自定义的属性,那么就需要创建自己的命名空间,在Android Studio中,第三方的控件都使用如下代码来引入命名空间。
xmlns:custom="http://schemas.android.com/apk/res-auto"
我们将引入的第三方控件的命名空间取名为custom,之后在XML文件中使用自定义的属性时,就可以通过这个命名空间来引用,代码如下:
<com.example.customview.TitleBar
android:id="@+id/title_bar"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@color/colorAccent"
custom:leftImageDrawable="@mipmap/return_white"
custom:rightImageDrawable="@mipmap/my_friend"
custom:title="视频列表"
custom:titleTextColor="#ffffff"
custom:titleTextSize="7sp"/>
重写View来实现全新的控件
创建一个自定义View,难点在于绘制控件和实现交互,这也是评价一个自定义View优劣的标准之一。通常需要继承View类,并重写它的onDraw()、onMeasure()等方法来实现绘制逻辑,同时通过重写onTouchEvent()等触控事件来实现交互逻辑。当然,也可以引入自定义属性,丰富自定义View的可定制性。
弧线展示图
绘制上图的自定义view,需要分别去绘制三个部分,分别是中间的圆形、中间的文字和外圈的弧线,代码如下。
public class CircleProgressView extends View {
private int mMeasureHeight;
private int mMeasureWidth;
private Paint mCirclePaint;
private float mCircleXY;
private float mRadius;
private Paint mArcPaint;
private RectF mArcRectF;
private float mSweepAngle;
private float mSweepValue = 66;
private Paint mTextPaint;
private String mShowText;
private float mShowTextSize;
public CircleProgressView(Context context) {
this(context, null);
}
public CircleProgressView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mMeasureWidth = MeasureSpec.getSize(widthMeasureSpec);
mMeasureHeight = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(mMeasureWidth, mMeasureHeight);
initView();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制圆
canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint);
//绘制弧线
canvas.drawArc(mArcRectF, 270, mSweepAngle, false, mArcPaint);
//绘制文字
canvas.drawText(mShowText, 0, mShowText.length(),
mCircleXY, mCircleXY + (mShowTextSize / 4), mTextPaint);
}
private void initView() {
float length;
if (mMeasureHeight >= mMeasureWidth) {
length = mMeasureWidth;
} else {
length = mMeasureHeight;
}
//圆中心x轴y轴坐标为屏幕宽度的一半
mCircleXY = length / 2;
//圆半径为屏幕宽度的四分之一
mRadius = (float) (length * 0.5 / 2);
mCirclePaint = new Paint();
//抗锯齿
mCirclePaint.setAntiAlias(true);
mCirclePaint.setColor(ContextCompat.getColor(getContext(), android.R.color.holo_blue_bright));
//绘制一个矩形范围,RectF参数为左上右下四个坐标
mArcRectF = new RectF((float) (length * 0.1), (float) (length * 0.1),
(float) (length * 0.9), (float) (length * 0.9));
mSweepAngle = (mSweepValue / 100f) * 360f;
mArcPaint = new Paint();
mArcPaint.setAntiAlias(true);
mArcPaint.setColor(ContextCompat.getColor(getContext(), android.R.color.holo_blue_bright));
mArcPaint.setStrokeWidth((float) (length * 0.1));
mArcPaint.setStyle(Paint.Style.STROKE);
mShowText = setShowText();
mShowTextSize = setShowTextSize();
mTextPaint = new Paint();
mTextPaint.setTextSize(mShowTextSize);
mTextPaint.setTextAlign(Paint.Align.CENTER);
}
private float setShowTextSize() {
this.invalidate();
return 50;
}
private String setShowText() {
this.invalidate();
return "Android Skill";
}
//强制刷新接口
public void forceInvalidate() {
this.invalidate();
}
//设置弧形比例值接口
public void setSweepValue(float sweepValue) {
if (sweepValue != 0) {
mSweepValue = sweepValue;
} else {
mSweepValue = 25;
}
this.invalidate();
}
}
音频条形图
实现一个动态的音频条形图,复杂点在于绘制的坐标计算和动画效果上,代码如下:
public class VolumeView extends View {
private int mWidth;
private int mRectWidth;
private int mRectHeight;
private Paint mPaint;
//音频条数量
private int mRectCount;
private int offset = 5;
private double mRandom;
private LinearGradient mLinearGradient;
public VolumeView(Context context) {
this(context, null);
}
public VolumeView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VolumeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.FILL);
mRectCount = 15;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//总控件长度
mWidth = getWidth();
//总控件高度
mRectHeight = getHeight();
//音频条长度:总控件长度的60%除以音频条个数
mRectWidth = (int) (mWidth * 0.6 / mRectCount);
// 创建LinearGradient对象
// 起始点坐标(-mViewWidth, 0) 终点坐标(0,0)
// 第一个,第二个参数表示渐变起点 可以设置起点终点在对角等任意位置
// 第三个,第四个参数表示渐变终点
// 第五个参数表示渐变颜色
// 第六个参数可以为空,表示坐标,值为0-1
// 如果这是空的,颜色均匀分布,沿梯度线。
// 第七个表示平铺方式
// CLAMP重复最后一个颜色至最后
// MIRROR重复着色的图像水平或垂直方向已镜像方式填充会有翻转效果
// REPEAT重复着色的图像水平或垂直方向
mLinearGradient = new LinearGradient(0, 0, mRectWidth, mRectHeight, Color.YELLOW,
Color.BLUE, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mRectCount; i++) {
//随机变化每个小矩形的高度
mRandom = Math.random();
float currentHeight = (float) (mRectHeight * mRandom);
canvas.drawRect(
//左坐标:总控件长度的40%/2加上音频条长度+5px的偏移量
(float) (mWidth * 0.4 / 2 + mRectWidth * i + offset),
currentHeight,
(float) (mWidth * 0.4 / 2 + mRectWidth * (i + 1)),
mRectHeight,
mPaint);
}
postInvalidateDelayed(300);
}
}