第一种方法,直接设置属性值,通过attrs.getAttributeResourceValue拿到这个属性值。
(1)在xml文件中设置属性值
(2)在构造函数中拿到这个值
public IconTextView(Context context, AttributeSet attrs) {
super(context, attrs);
resourceID = attrs.getAttributeResourceValue(null, "iconSrc", 0);
if(resourceID > 0) {
bitmap = BitmapFactory.decodeResource(getResources(), resourceID);
}
}
第二种方法,使用自己的命名空间
(1)注意在xml文件中,需要声明一个命名空间,形式为http:// + 这个VIEW的包名
(2)通过attrs.getAttributeResourceValue,其中第一个参数为命名空间。
//命名空间
private final String namespace = "http://com.example.activity"
publicIconTextView(Context context, AttributeSet attrs) {super(context, attrs);
resourceID= attrs.getAttributeResourceValue(namespace, "iconSrc", 0);//TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.IconTextView);//resourceID = array.getResourceId(R.styleable.IconTextView_iconSrc, 0);
if(resourceID > 0) {
bitmap=BitmapFactory.decodeResource(getResources(), resourceID);
}
}
第三种方法,通过自定义attrs.xml来实现
(1)自定义一个attrs.xml文件
(2)在xml文件中使用这一属性,注意此时命名空间的书写规范。
(3)在代码中使用context.obtainStyledAttributes获得属性值
package com.example.activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
public class IconTextView extends TextView {
//命名空间
private final String namespace = "http://com.example.activity";
//资源ID
private int resourceID = 0;
private Bitmap bitmap;
public IconTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.IconTextView);
resourceID = array.getResourceId(R.styleable.IconTextView_iconSrc, 0);
if(resourceID > 0) {
bitmap = BitmapFactory.decodeResource(getResources(), resourceID);
}
}
@Override
public void onDraw(Canvas canvas) {
if (bitmap != null) {
Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Rect target = new Rect();
int textHeight = (int)getTextSize();
target.left = 0;
target.top =(int)(getMeasuredHeight() - getTextSize()) / 2 + 1;
target.bottom = target.top + textHeight;
target.right = (int)(textHeight * (bitmap.getWidth() / (float)bitmap.getHeight()));
canvas.drawBitmap(bitmap, src, target, getPaint());
canvas.translate(target.right + 2, 0);
}
super.onDraw(canvas);
}
}
原文:http://www.cnblogs.com/hubing/p/4715047.html