I want to squeeze as much text as possible into one TextView of a widget, so I want to hyphenate the text contents of that particular TextView. The easiest way to retrieve the size of the TextView, I figure out, would be to inflate the whole widget with the size of the display. Then I would increase the text contents of the TextView and watch when the number of lines property changes, so that I know where to put the hyphen ('-').
This off-screen measuring works, but it seems that I'm setting some dimensions wrong, as the off-screen method detects new lines earlier than what is drawn on the actual widget, i.e. the actual widget seems to be wider than what I reproduce off-screen.
What am I doing wrong? Or is there another way to achieve what I want?
Here's some code:
1) The off-screen text measurement
String adaptText(String text) {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
// I'm aware these methods are deprecated, but the results are identical
// when I'm using the new method: display.getSize(point)
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();
LinearLayout root = new LinearLayout(this);
LinearLayout sampleLayout = (LinearLayout) LinearLayout.inflate(this,
R.layout.kal_medium, root);
sampleLayout.measure(displayWidth, displayHeight);
sampleLayout.layout(0, 0, displayWidth, displayHeight);
TextView saintsView = (TextView) sampleLayout.findViewById(R.id.saints);
StringBuilder textBuilder = new StringBuilder(); // result holder
int numLines = 1; // there's always one line at least
int len = text.length();
for (int i = 0; i < len; i++) {
saintsView.setText(textBuilder);
if (saintsView.getLineCount() > numLines) {
System.out.println("=========BROKEN AT:" + textBuilder);
// here goes the code that inserts the hyphen
numLines++;
}
textBuilder.append(text.charAt(i));
}
return textBuilder.toString();
}
2) The widget layout file: kal_medium.xml, not in whole.
<ImageView android:id="@+id/img_bg"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:src="@drawable/bg_post"/>
...
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/date"
android:layout_marginLeft="15dp"
android:layout_marginRight="12dp"
android:layout_marginTop="2dp"
android:padding="0dp">
...
<TextView android:id="@+id/saints"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:ellipsize="none"
android:textSize="19dp"
android:textStyle="bold"
android:gravity="center_vertical|left"
android:paddingTop="0dp"
android:layout_marginTop="-1dp"
android:paddingBottom="20dp"/>
</LinearLayout>