问题
I have to distribute text over a view uniformly. Have been unable to figure out a way that satisfies all screen sizes or even the common screen sizes. The layout I want to achieve is shown below.
The red box tells the textview I am trying to work on.
I have tried following approaches:
1) Try to use a image, with and without nine patch and it does not scale correctly. 2) try to use different size buckets like sw320 sw480 sw600 and sw720. And while it does fix this for devices I am able to test on, it is not dependable. I am putting different text sizes in these buckets.
I hate to use 24 texviews with table, grid or linear layout.
What other options do I have? The solution 2 was very frustrating to work with, navigating from dimens to layout and back again like about 20 times . There should be an easier way to do this, and if there isnt please tell me so.
回答1:
Use a custom View and override onDraw to draw the numbers. The layout containing the View can specify its size using dimensions (from res/values/), and the View will automatically work out what font size and spacing between the numbers based on those dimensions.
E.g.
Custom 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);
...
Getting the size:
@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
}
Doing the drawing:
@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;
}
}
That should draw something close, the first and last numbers won't draw correctly though, I'll leave that for you to fix.
EDIT
Keep in mind that you can't use wrap_content for this View's dimensions, because it doesn't specify a size to wrap by overriding onMeasure(). So it'll require specific sizes set, or match_parent.
来源:https://stackoverflow.com/questions/15151761/how-to-handle-difference-screen-sizes-so-that-a-textview-scales