Question

I have a graphical Android project and my primary trick for providing user interface functionality is to use drawrect and drawtext to draw a rectangle with a label on the screen. Then, I capture touch events and check to see if they occur in the rectangle -- when they do, voila, I have a button.

It may not be the most elegant method, but is seems to be working like a charm. However, not all of my labels look good all on one line, and I'd like to write them on two. I suppose I could write two separate lines and manually work out arranging the text to be nicely spaced and centered, but I'd like to avoid that if possible.

In Android, is there a simple way to split a text label and write it out in a single step??

Thanks, R.

Was it helpful?

Solution 2

In an Android application, you can create a Layout and populate it with a variety of widgets. One of these potential widgets is the button and if you use it, it WILL display your button label on more than one line if the label's length requires that...

However, my application is a SurfaceRunner, and this view doesn't support buttons, as far as I can tell. I do use a button-ish functionality by drawing various rectangles and checking for screen touches inside their boundaries. This works fine for my purposes, but does not, in any way, automate any of the display tasks (like the button widget does). In order to display a long label on two lines, it's necessary to do that explicitly in the code. Oh well.

Fortunately, it's only one additional line:

canvas.drawRoundRect (Button, ROUNDOVER_SIZE-1, ROUNDOVER_SIZE-1, paint);
canvas.drawText (Text1, Button.centerX() - paint.measureText (Text1)/2, Button.centerY() - 10, paint);
canvas.drawText (Text2, Button.centerX() - paint.measureText (Text2)/2, Button.centerY() + 20, paint);

Obviously, it would have been cooler if I had used something a tad more automatic than "10" and "20", but this does get the job done.

OTHER TIPS

I don't think there is a easy way to achieve this, you will have to measure the text and draw it with an offset that is ButtonWidth - TextWidth / 2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top