默认情况下,如果TextView的宽度超过文字的宽度,文字居中显示时,想要在文字的左边或者右边添加一个图片时,左边或者右边的文字就会默认以左边和右边开始排列,效果如下。
如果想要让,文字和图片一起居中显示,那么需要重写onDraw()方法,涉及的代码如下:
代码语言:javascript复制 @Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (null != drawables) {
Drawable drawableLeft = drawables[0];
Drawable drawableRight = drawables[2];
float textWidth = getPaint().measureText(getText().toString());
if (null != drawableLeft) {
setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
float contentWidth = textWidth getCompoundDrawablePadding() drawableLeft.getIntrinsicWidth();
if (getWidth() - contentWidth > 0) {
canvas.translate((getWidth() - contentWidth - getPaddingRight() - getPaddingLeft()) / 2, 0);
}
}
if (null != drawableRight) {
setGravity(Gravity.END | Gravity.CENTER_VERTICAL);
float contentWidth = textWidth getCompoundDrawablePadding() drawableRight.getIntrinsicWidth();
if (getWidth() - contentWidth > 0) {
canvas.translate(-(getWidth() - contentWidth - getPaddingRight() - getPaddingLeft()) / 2, 0);
}
}
if (null == drawableRight && null == drawableLeft) {
setGravity(Gravity.CENTER);
}
}
super.onDraw(canvas);
}
然后,再页面中引入我们自定义的TextView即可实现文字和图片的居中显示。