2015-12-30 218 views
0

我创建了自定义textview类,并且使用BackgroundColorSpan在后台应用颜色。如何在每行之前和之后添加空格。我非常感谢任何帮助。如何在每行的开头和结尾添加空格

final String test_str1 = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."; 


public class CustomTextView extends TextView { 
    public CustomTextView(Context context) { 
     super(context); 
     setFont(); 
    } 

    public CustomTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setFont(); 
    } 

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     setFont(); 
    } 

    private void setFont() { 
     Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/TEXT.ttf"); 
     setTypeface(font, Typeface.NORMAL); 

     Spannable myspan = new SpannableString(getText()); 
     myspan.setSpan(new BackgroundColorSpan(0xFF757593), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     txtview.setText(myspan); 
    } 
} 
+0

你有没有试过.append(“”); –

+0

你问是否将空格添加为字符(“”)或作为布局中的空白空间? – naXa

+0

http://stackoverflow.com/questions/6863974/android-textview-padding-between-lines –

回答

0

一个不会简单地在Java中添加或预先加上一个带有空格的字符串。在第一个例子中,你应该找一个为你做的图书馆。

我发现Apache Commons Lang是一个很好的字符串操作。它有StringUtils类以下方法:

public static String appendIfMissing(String str, CharSequence suffix, CharSequence... suffixes)
追加后缀为如果字符串不已经与任何后缀结束的字符串的结尾。

public static String prependIfMissing(String str, CharSequence prefix, CharSequence... prefixes) 如果字符串尚未以任何前缀开头,则将前缀添加到字符串的开头。

String上的两项操作都是无效的。

Linking the library到您的项目很容易。如果您使用Gradle,只需将此行添加到依赖关系

dependencies { 
    ... 
    compile 'org.apache.commons:commons-lang3:3.4' 
} 
0

另一种选择是使用JDK。 String.format()可用于左/右填充给定的字符串。

public static String padRight(String s, int n) { 
    return String.format("%1$-" + n + "s", s); 
} 

public static String padLeft(String s, int n) { 
    return String.format("%1$" + n + "s", s); 
} 

public static String pad(String s, int n) { 
    return padRight(padLeft(s, n), n); 
} 

// Usage example 
String myString = getText().toString(); 
Spannable myspan = new SpannableString(pad(myString, 1)); 
myspan.setSpan(new BackgroundColorSpan(0xFF757593), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
txtview.setText(myspan); 

参考文献:

  1. 在这个答案使用的方法Source;
  2. Format String Syntax | Java文档;
  3. SpannableString | Android文档;
  4. CharSequence | Android文档。
+0

我尝试了相同的代码,但它不起作用。 – jason

相关问题