android 带图片的文本框

基本原理

自定义一个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);
		
	}
	
	@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();
			
			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!!










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值