自定义控件0

自定义控件的最简单方法就是继承这个控件。

这次我们来重写一个TextView,让系统自带textview的左边加上一个图标。

效果如下:



实现方法:

package com.xys.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

public class IconTextView extends TextView {
	
	//命名空间
	private final String namespace="http://com.xys";
	//资源ID
	private int resourceID=0;
	private Bitmap bitmap;
	
	public IconTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		//该方法用于获得该控件属性的值
		resourceID=attrs.getAttributeResourceValue(namespace, "iconSrc",0);
		if(resourceID>0){
			bitmap=BitmapFactory.decodeResource(getResources(), resourceID);
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		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*bitmap.getWidth()/(float)bitmap.getHeight());
			canvas.drawBitmap(bitmap, src, target, getPaint());
			//将textview右移2像素
			canvas.translate(target.right+2, 0);
		}
		//父类的onDrow一定要在translate方法后执行
		super.onDraw(canvas);
	}
}
布局文件中的使用方法:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mobile="http://com.xys"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world">
    </TextView>
    
    <com.xys.widget.IconTextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="IconTextView"
        mobile:iconSrc="@drawable/folder" >

    </com.xys.widget.IconTextView>

</RelativeLayout>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值