---
title: "android"
author: "liangxianfu5811"
date: "2015-05-05T16:00:28Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2015-05-05T16:00:28Z"
id: 2208610
url: "https://love5811.iteye.com/blog/2208610"
---

在/values/目录下新建attr.xml文件，内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="LabelView">
        <attr format="string" name="text" />
        <attr format="color" name="textColor" />
        <attr format="dimension" name="textSize" />
    </declare-styleable>

</resources>
attr.xml文件就是我们自定义的属性文件。
在main.xml布局文件中使用自定义的属性：
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:labelview="http://schemas.android.com/apk/res/com.study.app.android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.study.app.android.LabelView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        labelview:text="自定义labelview控件"
        labelview:textColor="#ffcecece"
        labelview:textSize="20sp" >
    </com.study.app.android.LabelView>

</LinearLayout>
注意：首先将自定义属性引用进来xmlns:labelview="http://schemas.android.com/apk/res/com.study.app.android",其中labelview任意命名，com.study.app.android是应用的包名。
这样在代码中就可以使用自定义属性了
package com.study.app.android;
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;

public class LabelView extends View {
	private Paint mTextPaint;
	private String mText;
	private int mAscent;

	public LabelView(Context context) {
		super(context);
		initLabelView();
	}

	public LabelView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initLabelView();

		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.LabelView);

		CharSequence s = a.getString(R.styleable.LabelView_text);
		if (s != null) {
			setText(s.toString());
		}
		setTextColor(a.getColor(R.styleable.LabelView_textColor, 0xFF000000));

		int textSize = a.getDimensionPixelOffset(
				R.styleable.LabelView_textSize, 0);
		if (textSize > 0) {
			setTextSize(textSize);
		}

		a.recycle();
	}

	private final void initLabelView() {
		mTextPaint = new Paint();
		mTextPaint.setAntiAlias(true);
		mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
		mTextPaint.setColor(0xFF000000);
		setPadding(3, 3, 3, 3);
	}

	public void setText(String text) {
		mText = text;
		requestLayout();
		invalidate();
	}

	public void setTextSize(int size) {
		mTextPaint.setTextSize(size);
		requestLayout();
		invalidate();
	}
	public void setTextColor(int color) {
		mTextPaint.setColor(color);
		invalidate();
	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(measureWidth(widthMeasureSpec),
				measureHeight(heightMeasureSpec));
	}

	private int measureWidth(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		if (specMode == MeasureSpec.EXACTLY) {
			result = specSize;
		} else {
			result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
					+ getPaddingRight();
			if (specMode == MeasureSpec.AT_MOST) {
				result = Math.min(result, specSize);
			}
		}

		return result;
	}

	private int measureHeight(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		mAscent = (int) mTextPaint.ascent();
		if (specMode == MeasureSpec.EXACTLY) {
			result = specSize;
		} else {
			result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop()
					+ getPaddingBottom();
			if (specMode == MeasureSpec.AT_MOST) {
				result = Math.min(result, specSize);
			}
		}
		return result;
	}
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent,
				mTextPaint);
	}
}
参考文章：
declare-styleable：自定义控件的属性
http://blog.csdn.net/congqingbin/article/details/7869730

Android 深入理解Android中的自定义属性
http://blog.csdn.net/lmj623565791/article/details/45022631

Android资源文件res的使用详解（strings,layout,drawable,arrays等）
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2013/0204/838.html