剖析API Demos中的LabelView (四)

2014-11-24 11:44:56 · 作者: · 浏览: 43
tyled 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可见,那么将会系统调用onDraw(...)方法
invalidate();
}

/**
* 设置文本颜色
* Sets the text color for this label.
* @param color ARGB value for the text
*/
public void setTextColor(int color) {
mTextPaint.setColor(color);
invalidate();
}

/**
* 测量View和它的内容,并决定测量宽度和测量高度
* 这个方法被 measure(int, int)所调用
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 覆盖onMeasure时必须调用此方法,否则会抛出measurement 运行时异常
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}

/**
* 决定这个view的宽度
* @param measureSpec A measureSpec packed into an int
* @return The width of the view, honoring constraints from measureSpec
*/
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = Meas