展会信息港展会大全

android 带图片的文本框
来源:互联网   发布日期:2015-11-15 10:12:22   浏览:2361次  

导读:基本原理自定义一个IconTextView类继承自TextView,添加iconsrc属性,表示图片。重新onDraw方法,将图片绘制到textVIew前面,然后将textView右移。废话不多说了,直接代码就明白。package com.zb;import androi......

基本原理

自定义一个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"要和代码里面定义的一样。

赞助本站

人工智能实验室

相关热词: 文本框 图片

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港