Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

margin set to first line of textView

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..

like image 810
ShineDown Avatar asked Oct 07 '11 07:10

ShineDown


2 Answers

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.lenght() > 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.

like image 126
Alexey Avatar answered Oct 20 '22 02:10

Alexey


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.

like image 41
Michell Bak Avatar answered Oct 20 '22 03:10

Michell Bak