安卓自定义带图片的TextView标签组件, 效果图:
在 activety_main.xml 内部添加自定义标签, 使用了自定义的命名空间:xmlns:nono="http://com.demo0.nono" ,在java文件中也要根据命名空间获取属性值:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:nono="http://com.demo0.nono"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".main">
<com.demo0.nono.icontext.IconTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
nono:iconSrc="@drawable/pic"
android:text="smile"/>
<com.demo0.nono.icontext.IconTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
nono:iconSrc="@drawable/pic"
android:textSize="24dp"
android:text="smile 24 dp"/>
<com.demo0.nono.icontext.IconTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
nono:iconSrc="@drawable/pic"
android:textSize="36dp"
android:text="smile 36 dp"/>
<com.demo0.nono.icontext.IconTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
nono:iconSrc="@drawable/pic"
android:textSize="50dp"
android:text="smile 50 dp"/>
</LinearLayout>
定义 com.demo0.nono.icontext.IconTextView 类, 该类继承TextView并,重写onDraw方法 , 在IconTextView的构造函数中获取函数自定义属性, 并初始化bitmap资源,以备后用:
package com.demo0.nono.icontext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by nono on 2018/4/6.
*/
public class IconTextView extends TextView {
private final String namespace = "http://com.demo0.nono";
private int resourceId = 0;
private Bitmap bitmap;
public IconTextView(Context context, AttributeSet attrs) {
super(context, attrs);
resourceId = attrs.getAttributeResourceValue(namespace, "iconSrc", 0);
if(resourceId>0) {
bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
}
}
@Override
protected void onDraw(Canvas canvas) {
if(bitmap!=null) {
Rect src = new Rect();
Rect target = new Rect();
src.left = 0;
src.top = 0;
src.right = bitmap.getWidth();
src.bottom = bitmap.getHeight();
target.top = 0;
target.left = 0;
target.bottom = getMeasuredHeight();
int wid = (getMeasuredHeight()*bitmap.getWidth())/bitmap.getHeight();
target.right = wid;
canvas.drawBitmap(bitmap, src, target, getPaint());
canvas.translate(wid,0);
}
super.onDraw(canvas);
}
}
来源:oschina
链接:https://my.oschina.net/u/4281503/blog/4017756