android TextView 数字 17 为什么不能绝对居中
Android的TextView默认是基于文本的baseline对齐的,对于单行文本,可以通过设置gravity属性为center来实现水平居中对齐。但是,对于数字17这种数字字符,它的字符高度不同于其他字符,因此无法完全居中。
要解决这个问题,可以尝试以下方法之一:
- 使用android:gravity="center_vertical"属性来实现垂直居中对齐,这样数字17会在TextView的垂直中心位置。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="17"
android:gravity="center_vertical"
/>
- 自定义TextView并重写它的onDraw方法,在绘制文本之前,手动调整文本的绘制位置,使其居中。
public class CenteredTextView extends TextView {
public CenteredTextView(Context context) {
super(context);
}
public CenteredTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenteredTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
// 获取TextView的宽度和高度
int width = getWidth();
int height = getHeight();
// 获取文本的宽度
Paint paint = getPaint();
String text = getText().toString();
float textWidth = paint.measureText(text);
// 计算文本的绘制位置,使其水平居中
float x = (width - textWidth) / 2f;
// 计算文本的baseline位置,使其垂直居中
Paint.FontMetrics fm = paint.getFontMetrics();
float y = height / 2f - (fm.descent + fm.ascent) / 2f;
// 绘制文本
canvas.drawText(text, x, y, paint);
}
}
然后,在布局文件中使用自定义的CenteredTextView:
<com.example.app.CenteredTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="17"
/>
这样就可以实现数字17的绝对居中了
原文地址: https://www.cveoy.top/t/topic/ixMB 著作权归作者所有。请勿转载和采集!