Android中带文字的ImageButton的实现

import android.content.Context;
import android.graphics.Canvas;
import   android.graphics.Paint;
import android.graphics.Typeface;
import   android.widget.ImageButton;  
public class Butt extends ImageButton
{
 private String text = null;  //要显示的文字
 private int color;//文字的颜色
 
 public Butt(Context context)
 {
  super(context);
 }
 
 public void setText(String text)
 {
  this.text = text;//设置文字
 this.invalidate();  //通知刷新
 }
 
 public void setColor(int color)
 {
  this.color = color;//设置文字颜色
 }
 
 protected void onDraw(Canvas canvas)
 {
  super.onDraw(canvas);
  
  if(this.text != null)
  {
   Paint paint=new Paint();
   paint.setTextAlign(Paint.Align.CENTER);
   paint.setAntiAlias(true);
   paint.setTypeface(Typeface.create("宋体",      Typeface.BOLD_ITALIC));
   paint.setColor(color);
   paint.setTextSize(this.getHeight()/6);
   canvas.drawText(this.text,this.getWidth()/2,this.getHeight()-(float)(paint.getTextSize()-2)/2,paint);//绘制文字
  }
 }
}

 

上一篇:安卓学习笔记(嵌套布局和ImageButton按钮和约束布局管理器)


下一篇:Android开发:ImageButton背景色与背景图片融为一体的方法