• 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#

  • 相关阅读:
    (十一)设置关闭多核cpu的核
    (十)修改开发板主频
    (九)How to use the audio gadget driver
    (8)全志A64查看寄存器
    内存溢出问题配置
    百度数据库优化经验
    如何让sql运行的更快
    百度性能优化
    spring ioc原理
    JNDI
  • 原文地址:https://www.cnblogs.com/shanzei/p/2434500.html
Copyright © 2020-2023  润新知