Drawable

Android中,Drawable是绘图中的一个非常一般化的概念, 它是能够在Canvas上绘制图形,而且相比于View, 并不需要去考虑measurelayout,仅仅只要去考虑如何draw

Android中的Drawable资源非常丰富,有多种不同类型的Drawable

Drawable相关的包为:android.graphics.drawable, 下面是Drawable的类图:

Android中的很多资源都可以用XML文件描述。Drawable资源也可以。 在res/drawableres/drawable-xx目录下的XML文件都是。

下面是XML文件中的根标签与具体的Drawable类型的对应关系:

public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
	throws XmlPullParserException, IOException {
	Drawable drawable;

	final String name = parser.getName();

	if (name.equals("selector")) {
		drawable = new StateListDrawable();
	} else if (name.equals("level-list")) {
		drawable = new LevelListDrawable();
	} else if (name.equals("layer-list")) {
		drawable = new LayerDrawable();
	} else if (name.equals("transition")) {
		drawable = new TransitionDrawable();
	} else if (name.equals("color")) {
		drawable = new ColorDrawable();
	} else if (name.equals("shape")) {
		drawable = new GradientDrawable();
	} else if (name.equals("scale")) {
		drawable = new ScaleDrawable();
	} else if (name.equals("clip")) {
		drawable = new ClipDrawable();
	} else if (name.equals("rotate")) {
		drawable = new RotateDrawable();
	} else if (name.equals("animated-rotate")) {
		drawable = new AnimatedRotateDrawable();
	} else if (name.equals("animation-list")) {
		drawable = new AnimationDrawable();
	} else if (name.equals("inset")) {
		drawable = new InsetDrawable();
	} else if (name.equals("bitmap")) {
		// noinspection deprecation
		drawable = new BitmapDrawable(r);
		if (r != null) {
			((BitmapDrawable) drawable).setTargetDensity(r
					.getDisplayMetrics());
		}
	} else if (name.equals("nine-patch")) {
		drawable = new NinePatchDrawable();
		if (r != null) {
			((NinePatchDrawable) drawable).setTargetDensity(r
					.getDisplayMetrics());
		}
	} else {
		throw new XmlPullParserException(parser.getPositionDescription()
				+ ": invalid drawable tag " + name);
	}

	drawable.inflate(r, parser, attrs);
	return drawable;
}