12

I want to set start margin only for the first line of TextView (Not first line of each paragraph)? I have used the following code:

SpannableString s = new SpannableString("this is a test"+"\n"+"this is a test");
s.setSpan(new android.text.style.LeadingMarginSpan.Standard(30, 0), 0, s.length(), 0);
textView .setText(s);

Here start margin is getting set for all lines of the Paragraph.. I don't want that. I want start margin to be applied for first line only.. Pls help..

Rick
  • 1,177
  • 1
  • 19
  • 27
ShineDown
  • 1,881
  • 3
  • 21
  • 29

2 Answers2

6

You actually already answered your own question.
All you need to do is to set span lenght to 1 instead of s.length().

if (s.length() > 0) {
    s.setSpan(new android.text.style.LeadingMarginSpan.Standard(30, 0), 0, 1, 0);
}

That way margin will only be applied to the first paragraph.

Alex
  • 781
  • 10
  • 23
Alexey
  • 7,262
  • 4
  • 48
  • 68
2

As it has been suggested here, I also think the best solution is to simply add a few spaces at the beginning. If you only need the margin space at the very first line of the TextView, I don't see any reason why you'd need to do something really advanced.

If you need to change or use the text in the TextView at a later point, you can just use the substring() method to get only a part of the string, i.e. s.substring(2, s.length());

It's not a perfect solution, but I think it'll do.

Michell Bak
  • 13,182
  • 11
  • 64
  • 121
  • The trouble is diff characters need diff length of UI to show, (ex: 'm' needs more length than 'i'), and a space length is not equal with all characters length. – Phong Nguyen Dec 04 '17 at 05:06