Android 自定义带文本的ImageButton:
/**
* 带文字的ImageButton。 后期需求更改,toolbar右上角按钮要加文字描述,因不想更改布局,所以使用自定义控件
*
*/
public class ImageButtonWithText extends ImageButton {
/**
* @uml.property name="text"
*/
private String text = null; // 要显示的文字
/**
* @uml.property name="color"
*/
private int color = Color.WHITE; // 文字的颜色
/**
* @uml.property name="width"
*/
private int width;
/**
* @uml.property name="height"
*/
private int height;
/**
* @uml.property name="mTextSize"
*/
private float mTextSize = 30;
Paint paint;
public ImageButtonWithText(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
}
public void setTextSize(float textSize) {
mTextSize = textSize;
postInvalidate();
}
/**
* @param text
* @uml.property name="text"
*/
public void setText(String text) {
this.text = text; // 设置文字
width = this.getMeasuredWidth();
height = this.getMeasuredHeight();
invalidate();
}
/**
* @param color
* @uml.property name="color"
*/
public void setColor(int color) {
this.color = color; // 设置文字颜色
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (text == null)
return;
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(mTextSize);
paint.setColor(color);
// FontMetrics对象
FontMetrics fontMetrics = paint.getFontMetrics();
width = canvas.getWidth();
height = canvas.getHeight();
// 计算文字高度
float fontHeight = fontMetrics.bottom - fontMetrics.top;
// 计算文字baseline
float textBaseY = height - (height - fontHeight) / 2
- fontMetrics.bottom;
canvas.drawText(text, width / 2, textBaseY, paint); // 绘制文字
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
color = getResources().getColor(R.color.button_click);
invalidate();
break;
case MotionEvent.ACTION_UP:
color = Color.WHITE;
invalidate();
break;
default:
break;
}
return super.onTouchEvent(event);
}
}
整个自定义看起来挺简单的,也的确挺简单的,但是自己用的时候被自己蠢到了:
<span style="white-space:pre"> </span>btn_right = (ImageButtonWithText) toolbarView.findViewById(R.id.btn_right);
btn_right.setText("文本");
btn_right.setVisibility(View.VISIBLE);
btn_right.setTextSize(R.dimen.text_medium_size);
惊喜就来了,一运行,布局是存在的,但是整个文本不见了!调试了半天才发现
setTextSize(R.dimen.text_medium_size)
设置的一个地址,一个很大的值,“大象无形”就是看不见文本,正确的方式如下:
btn_right.setTextSize(getResources().getDimensionPixelSize(R.dimen.text_medium_size));
是不是很无语,又是一个“什么鬼,原来这么简单”的问题!