android 带图片的文本框
生活随笔
收集整理的這篇文章主要介紹了
android 带图片的文本框
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
基本原理
自定義一個(gè)IconTextView類繼承自TextView,添加iconsrc屬性,表示圖片。
重新onDraw方法,將圖片繪制到textVIew前面,然后將textView右移。
廢話不多說(shuō)了,直接代碼就明白。
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();//原圖區(qū)域
Rect target=new Rect();//目標(biāo)區(qū)域
src.left=0;
src.top=0;
src.right=bitmap.getWidth();
src.bottom=bitmap.getHeight();
int textHeight=(int) getTextSize();
target.left=0;
//計(jì)算圖像復(fù)制區(qū)域的縱坐標(biāo),
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());
//向右移動(dòng)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="妞給爺笑一個(gè)" />
<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="妞給爺笑一個(gè)" />
</LinearLayout>
代碼很簡(jiǎn)單把。
這里需要幾個(gè)地方,namespace?xmlns:zb="http://com.zb.text"要和代碼里面定義的一樣。
原文:http://blog.csdn.net/hopezhangbo/article/details/7351290#
轉(zhuǎn)載于:https://www.cnblogs.com/shanzei/archive/2012/04/06/2434500.html
總結(jié)
以上是生活随笔為你收集整理的android 带图片的文本框的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 孕妇梦到生女儿准吗
- 下一篇: 判断整数序列是不是二元查找树的后序遍历结