第一步,写一个类继承TextView类
public class SelfTextView extends TextView {
private Drawable drawable;
public SelfTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyTextView);
drawable = a.getDrawable(R.styleable.MyTextView_pic);
}
// Drawable转换成Bitmap
private Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof NinePatchDrawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
} else {
return null;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Bitmap image = drawable2Bitmap(drawable);
if (image != null) {
Paint pt = new Paint();
pt.setARGB(255, 66, 66, 66);
// 消除锯齿
pt.setAntiAlias(true);
// 居中显示图片
int imageX = (int) (this.getWidth() - image.getWidth()) / 2;
canvas.drawBitmap(image, imageX, 2, pt);
canvas.save();
/*
* pt.setColor(Color.GREEN); pt.setStrokeWidth(5);
* canvas.drawLine(0, 0, this.getWidth(), 0, pt);
*/
}
}
}
第二步:在res文件的value文件中定义attrs.xml文件
<resources>
<declare-styleable name="MyTextView">
<attr name="pic" format="reference"></attr>
</declare-styleable>
</resources>
第三步:写layout布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:attrstest="http://schemas.android.com/apk/res/com.itheima.androidtest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.itheima.androidtest.SelfTextView
android:id="@+id/buyHomeTab"
style="@style/textViewStyle"
android:layout_width="60dip"
android:layout_height="50dip"
android:checked="true"
android:paddingTop="5dip"
android:text="@string/home"
android:background="@drawable/flower"
attrstest:pic="@drawable/bg_navigation_item" />
</LinearLayout>