1

I’m developing an android app that gets objects from a server and shows them in a simple list.

I’m trying to figure out how to deal with long object’s titles : Every title populates a designated multi-line TextView. If a title is longer than 16 characters, it messes with my desired UI.

There are two scenarios I need to solve -

1). If the title is longer than 16 characters & contains more than one word, I need to split the words into different lines (I tried to .split("") and .trim(), but I don’t want to use another view, just break a line in the same one, and the use in ("") seems unreliable to me).

2). If the title is longer than 16 characters and contains only one long word, I only need to change font size specifically.

Any ideas for a good and reliable solution?

Thanks a lot in advance.

sschrass
  • 7,014
  • 6
  • 43
  • 62
NShemesh
  • 75
  • 1
  • 7

4 Answers4

1

use SpannableString for a single view

For title:

 SpannableString titleSpan = new SpannableString("title String");
 titleSpan.setSpan(new RelativeSizeSpan(1.3f), 0, titleSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

for Message

SpannableString messageSpan = new SpannableString("Message String");
messageSpan.setSpan(new RelativeSizeSpan(1.0f), 0, messageSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

set in TextView

 tvTermsPolicyHeading.setText(TextUtils.concat(titleSpan, messageSpan));
Milan Pansuriya
  • 2,521
  • 1
  • 19
  • 33
0

You can split and then concatenate the words using "\n" if there are more than one words. In case of long word You can see this question here Auto-fit TextView for Android

Mohd Akbar
  • 111
  • 5
0

Code like below it will work as you need

String title; //your title

//find length of your title
int length = title.length();

if (length>16){
string[] titles = myString.split("\\s+");

int size = titles.length;

if (size < 2){
      yourTextview.setText(title);
   // reduce the text size of your textview
}else {
  String newTitle= "";
for (int i=0;i<titles.length;i++){
  newTitle = titles[i]+"\n"
}
  yourTextview.setText(newTitle);

}
}
Jarin Rocks
  • 975
  • 10
  • 17
0

try this:

if(title.split(" ").size > 1){
    String line1 = title.substring(0, 16);
    int end = line1.lastIndexOf(" ");
    titleTextView.setText(title.substring(0,end) + "\n" + 
    title.substring(end+1,title.size-1);
}else{
    titleTextView.setText(title);
    titleTextView.setTextSize(yourTextSize);
}

this code should work perfectly for your case.

amm965
  • 399
  • 5
  • 14