基本原理
自訂一個IconTextView類繼承自TextView,添加iconsrc屬性,表示圖片。
重新onDraw方法,將圖片繪製到textVIew前面,然後將textView右移。
廢話不多說了,直接代碼就明白。
package com.zb;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Rect;import android.graphics.drawable.BitmapDrawable;import android.util.AttributeSet;import android.view.View;import android.widget.TextView;public class IconTextView extends TextView {private final String nameSpace="http://com.zb.text";//儲存映像資源ID的變數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);}@Overrideprotected 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();int textHeight=(int) getTextSize();target.left=0;//計算映像複製地區的縱座標,target.top=(int) (((getMeasuredHeight()-getTextSize())/2)+1);target.bottom=target.top+textHeight;target.right=(int) (textHeight*((float)bitmap.getWidth()/bitmap.getHeight()));//繪製canvas.drawBitmap(bitmap, src, target, getPaint());//向右移動TextView的的距離canvas.translate(target.right+2,0);}super.onDraw(canvas);}}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:zb="http://com.zb.text" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <com.zb.IconTextView android:id="@+id/iconText1" android:layout_width="fill_parent" android:layout_height="wrap_content" zb:iconSrc="@drawable/small" android:text="妞給爺笑一個" /> <com.zb.IconTextView android:id="@+id/iconText1" android:layout_width="fill_parent" android:layout_height="wrap_content" zb:iconSrc="@drawable/small" android:textSize="30dp" android:text="妞給爺笑一個" /></LinearLayout>
代碼很簡單把。
布局檔案
這裡需要幾個地方,namespace xmlns:zb="http://com.zb.text"要和代碼裡面定義的一樣。
ok!!