Can I limit TextView's number of characters?
What I have now is a ListView of TextView elements. each TextView element displays a text (the text length varies from 12 words to 100+). What I want is to make these TextViews display a portion of the text (let's say 20 word or roughly 170 chars).
How to limit the TextView to a fixed number of characters?
Here is an example. I limit the sizewith the maxLength attribute, limit it to a single line with maxLines attribute, then use the ellipsize=end to add a "..." automatically to the end of any line that has been cut-off.
<TextView
android:id="@+id/secondLineTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:maxLength="10"
android:ellipsize="end"/>
If your not interested in xml solutions maybe you can do this:
String s="Hello world";
Textview someTextView;
someTextView.setText(getSafeSubstring(s, 5));
//the text of someTextView will be Hello
...
public String getSafeSubstring(String s, int maxLength){
if(!TextUtils.isEmpty(s)){
if(s.length() >= maxLength){
return s.substring(0, maxLength);
}
}
return s;
}