Blupixel IT Blog – Computer Science and Web Developing Articles

Offical Blog of Blupixel IT Srl

Convert text to table in Android SDK

In Android, the management of text can be really difficult.

To visualize a text in a tidy way, like in a table, for example, you have to create a special layout, add elements and fill each cell with one portion of the text.

But if you have a normal text and you want to align it as in a table, using a normal TextView, you can use the following trick, that calculate the width of the text and add as many white spaces as needed to reach the fixed width of the cell.

String lines[] = getItem(position).toString().split("\n");
String print = "";
String parts[] = null;
String tmp = "";
int weight = 0;
for (int i=0; i < lines.length; i++) {
   if (!lines[i].equalsIgnoreCase("")) {
	   parts = lines[i].split(":", 2);
	   tmp = "";
	   Paint textPaint = text.getPaint();
	   float width = textPaint.measureText(parts[0]);
	   float wslength = textPaint.measureText(" ");
	   for (int j = 0; j < (220 - Math.round(width))/Math.round(wslength); j++) {
		   tmp = tmp + " ";
	   }
	   if (print.equalsIgnoreCase("")) {
		   print = print + parts[0] + tmp + Html.fromHtml(""+parts[1]+"");
	   } else {
		   print = print + "\n" + parts[0] + tmp + parts[1];
	   }
   }
}

In the first part I split the string into lines, using the newline as the separator, Then I loop for each line and if it is not void I proceed.

I split every line in “cells” using the “:” character as sperator (in this case I consider I will have only 2 cells), the I take the rendered width of the text and I add as many spaces as needed to reach a width of 220.

If you have more than 2 cells, you will need to perform the same operation on all the cells ecluded the last one.

If it is the first row, I will use the bold as it is an header.

Then you can insert the print variable into a TextView or AlertDialog having the “table effect”.

Happy coding

Your email address will not be published. Required fields are marked *

*

lKjA

Please type the text above: