android 带图片的文本框
生活随笔
收集整理的這篇文章主要介紹了
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"要和代碼里面定義的一樣。
原文:http://blog.csdn.net/hopezhangbo/article/details/7351290#
轉載于:https://www.cnblogs.com/shanzei/archive/2012/04/06/2434500.html
總結
以上是生活随笔為你收集整理的android 带图片的文本框的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 孕妇梦到生女儿准吗
- 下一篇: 做梦梦到孩子流产了下体流血怎么回事