androidfontmetrics

Android: Programmatically calculate Listview Font Metrics


I have a String and I need to truncate the string such that it fits on one line in a ListView.

Can anyone point me in the right direction?


Solution

  • You need to specify that in the XML of your list item row file.

    These are the attributes you need to play with on your TextView;

    android:singleLine="true"
    android:maxLength="someLengthofCharacters(int)"
    android:ellipsize="end"  //if you want an ellipse to be appended to the end of your String
    

    EDIT: Try this approach to set the max character length of your TextView programmatically

    TextView tv = new TextView(this);
    int maxLength = 10;
    InputFilter[] fArray = new InputFilter[1];
    fArray[0] = new InputFilter.LengthFilter(maxLength);
    tv.setFilters(fArray)
    

    and set single line to true by using

    TextView.setSingleLine or TextView.setLines(1)