Reputation: 6081
I got dynamic texts. The problem is that they should all fit into one line. Is there a way I can find out if the android device would make a text with a newline in order to display the whole text?
Basically what I want to do is, to shorten the text if the device can't display all on one line. Is this possible?
Currently I'm just displaying the data and its making a new line every time it's too long. I figured out I could split the string after 15 characters but I want to make it dependent on the screen width.
I thought I may can get the screen width, but then? Any suggestions to this?
Upvotes: 0
Views: 1388
Reputation: 9814
Is this what you mean?
TextView.setLines(1);
You can also set number of lines in the XML file. This way you always have one line and if it is too long it sets three dots at the end.
Edit:
TextView.setLines(1); // Sets the number of lines for your textview
int start = textView.getLayout().getLineStart(1); // Gets the index for the start position of your text.
int end = textView.getLayout().getLineEnd(1); // Gets the index for the end position of the first line.
String date = "| 18 Oktober 2013 |"; // I don't know how you get the date so this is an example
//Set the text with only the first line and date, so you only have one line with the date.
textView.setText(textView.getText().substring(start, end - date.length()) + date);
Upvotes: 1
Reputation: 4716
To know the width (in pixels) of a string that you intend to display, you need to get the font's metrics, then use it to compute the length of the given string. For example, you might have:
FontMetrics metrics = this.getFontMetrics(theFont);
int width = metrics.stringWidth("sample string");
Now, I'm not sure what you want to do, but assuming you want to truncate the string then add "..." after it, then you might want to go with something like:
FontMetrics metrics = this.getFontMetrics(theFont);
int maxWidth = /* Get the field's width */;
String myString = "sample string";
if (metrics.stringWidth(myString) > maxWidth) {
do {
myString = myString.substring(0, myString.length - 1);
} while (metrics.stringWidth(myString + "…") > maxWidth)
myString = myString + "…";
}
Note that this method should work fine when manipulating short strings. For longer texts, there is a faster approach, which imply the use of an AttributedString and a LineBreakMesurer. Have a look at Oracle's Text API Trail.
Upvotes: 0