使用自定义视图并覆盖 onDraw 来绘制数字。包含 View 的布局可以使用尺寸(来自 res/values/)指定其大小,并且 View 将根据这些尺寸自动计算出字体大小和数字之间的间距。
例如
自定义视图:
public class ColumnNumbersView extends View
{
private final static int NUMBER_OF_COLUMNS = 25;
private float textSize;
private final Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
...
获取尺寸:
@Override
protected void onLayout(...
{
super.onLayout(...
// work out our text size from getHeight()
textSize = getHeight()/2; // or something like that
// work out the spacing between the numbers along the x axis
textPosXInc = (getWidth() / NUMBER_OF_COLUMNS) / 2; // or something like that
}
做图:
@Override
protected void onDraw(final Canvas canvas)
{
super.onDraw(canvas);
int x = 0;
for(int i=0; i < NUMBER_OF_COLUMNS; i++)
{
final String number = String.valueOf(i);
final int halfWidth = textPaint.measureText(number) / 2;
canvas.drawText(number, x - halfWidth, 0, textPaint);
x += textPosXInc;
}
}
那应该会接近一些东西,但是第一个和最后一个数字不会正确绘制,我会留给你解决。
编辑
请记住,您不能将 wrap_content 用于此视图的尺寸,因为它没有通过覆盖 onMeasure() 来指定要包装的尺寸。所以它需要设置特定的尺寸,或者 match_parent。