1

I want to Limit the maximum no of words in a TextView instead of maximum no of characters.

My android code is like:

    <TextView
        android:id="@+id/orgSummary_desc_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="10dp"
        android:gravity="top"
        android:maxLength="100" 
        android:textSize="@dimen/subtitle_text"
        android:autoLink="web"
    />

I am setting a long text from my activity class and the result i am getting that some no of characters are chopped off. Instead i want the word.

Simon Marquis
  • 7,248
  • 1
  • 28
  • 43
anand
  • 1,711
  • 2
  • 24
  • 59

3 Answers3

1

Try this:

final int MAX_COUNT = 4;

TextView textView = /* your text view */
String text = "your long text comes here";

String[] segments = text.split(" ");
int wordsCount = segments.length;
if(wordsCount > MAX_COUNT) {
    text = "";
    for(int i = 0; i < MAX_COUNT; i += 1) {
        text += segments[i];
    }
    text += " Read more...";
}
textView.setText(text);
frogatto
  • 28,539
  • 11
  • 83
  • 129
1

You can use a custom join() method to only join the required word length:

final static int NB_OF_WORDS = 5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView textView  = findViewById(R.id.edit_text);
    final String text = /* */ ;

    String[] words = text.split(" ");
    textView.setText(words.length > NB_OF_WORDS ? join(" ", NB_OF_WORDS, words) : text);
}


public static CharSequence join(CharSequence delimiter, int length, Object[] tokens) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < tokens.length; i++) {
        if (i > length) {
            break;
        }
        if (i > 0) {
            sb.append(delimiter);
        }
        sb.append(tokens[i]);
    }
    return sb.toString();
}
Simon Marquis
  • 7,248
  • 1
  • 28
  • 43
0

Kotlin version

fun String.maxWord(max: Int, postfix: String = ""): String = split(" ").let { words ->
    if (words.size < max) return@let this

    words.take(max).joinToString(separator = " ", postfix = postfix).trim()
}
Zakhar Rodionov
  • 1,398
  • 16
  • 18