剖析API Demos中的LabelView (一)

2014-11-24 11:44:56 · 作者: · 浏览: 41

对于谷歌给我们提供的ApiDemo里有很多有学习参考价值的实例,今天来学习理解其中的一个实例类LabelView,此类

继承View,并对View中的onMeasure(),Ondraw()方法进行了重写,其中涉及到setMeasuredDimension() , MeasureSpec,Canvas,Paint,以及自定义

属性的一些应用。

像完全自定义控件(也就是继承View自定义控件),一般会想到覆盖onMeasure(),Ondraw(),

默认onMeasure()会总是设置一个100*100尺寸

关于自定义属性 可以参考 Android开发之自定义属性(Define Custom Attributes)

下面是主要实现代码


[java]
package com.example.labelview;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;


/**
* Example of how to write a custom subclass of View. LabelView
* is used to draw simple text views. Note that it does not handle
* styled text or right-to-left writing systems.
*
*/
public class LabelView extends View {
private Paint mTextPaint;
private String mText;
private int mAscent;

/**
* Constructor. This version is only needed if you will be instantiating
* the object manually (not from a layout XML file).
* @param context
*/
public LabelView(Context context) {
super(context);
initLabelView(); // 初始化
}

/**
* Construct object, initializing with any attributes we understand from a
* layout file. These attributes are defined in
* SDK/assets/res/any/classes.xml.
*
* @see android.view.View#View(android.content.Context, android.util.AttributeSet)
*/
public LabelView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView();
// 得到TypedArray 后面会利用它来获取自定义属性的值
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.LabelView);

// 获取自定义属性text的值
CharSequence s = a.getString(R.styleable.LabelView_text);
if (s != null) {
setText(s.toString());
}

// Retrieve the color(s) to be used for this view and apply them.
// Note, if you only care about supporting a single color, that you
// can instead call a.getColor() and pass that to setTextColor().
// 获取自定义属性textColor的值,并设置文本相应的颜色值
setTextColor(a.getColor(R.styleable.LabelView_textColor, 0xFF000000));

int textSize = a.getDimensionPixelOffset(R.styleable.LabelView_textSize, 0);
if (textSize > 0) {
setTextSize(textSize);
}

// 注意这里记得要回收 TypedArray
a.recycle();
}

// 初始化 paint,并对其设置相应的属性值
private final void initLabelView() {
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16);
mTextPaint.setColor(0xFF000000);
setPadding(10, 10, 10, 10);
}

/**
* Sets the text to display in this label
* @param text The text to display. This will be drawn as one line.
*/
public void setText(String text) {
mText = text;
requestLayout();
invalidate();
}

/**
* 设置文本大小
* Sets the text size for this label
* @param size Font size
*/
public void setTextSize(int size) {
mTextPaint.setTextSize(size);
// view 在layout上发生的改变(大小,位置),遂调用此方法
requestLayout();
// 使整个View无效,如果该View可见,那么将会系统