上面的代码不起作用,因为getAttributes()方法只返回迭代中当前char的属性
以下是我的解决方法:
我制作了自己的字符串生成器
请注意,我在字符串之间添加了一个空格
public class AttributedStringBuilder{
private AttributedString builString;
public AttributedStringBuilder(){
this.builString = new AttributedString("");
}
public void append(AttributedStringBuilder strings){
if(strings == null){
return;
}
this.append(strings.getBuilStirng());
}
public void append(AttributedString string){
if(string == null){
return;
}
this.builString = AttributedStringUtil.concat(this.builString, string," ");
}
public AttributedString getBuilStirng(){
return this.builString;
}
@Override
public String toString(){
return AttributedStringUtil.getString(this.builString);
}
}
还有一个实用类:
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.CharacterIterator;
public class AttributedStringUtil {
public static AttributedString concat(AttributedString first,AttributedString secound,String seperation){
String firstString = AttributedStringUtil.getString(first);
String secoundString = AttributedStringUtil.getString(secound);
String resultString = firstString + seperation + secoundString;
AttributedString result = new AttributedString(resultString);
AttributedStringUtil.addAttributes(result, first, secound, seperation.length());
return result;
}
public static AttributedString concat(AttributedString first,AttributedString secound){
return AttributedStringUtil.concat(first, secound,"");
}
private static void addAttributes(AttributedString result,AttributedString first,AttributedString secound,int seperationOffset){
AttributedCharacterIterator resultIterator = result.getIterator();
AttributedCharacterIterator firstIterator = first.getIterator();
AttributedCharacterIterator secoundIterator = secound.getIterator();
char resultCharacter = resultIterator.current();
int truePosition = 0;
int usePosition = 0;
while( resultCharacter != CharacterIterator.DONE)
{
usePosition = truePosition;
AttributedCharacterIterator it = AttributedStringUtil.getIterator(firstIterator, secoundIterator);
if(it == null){
break;
}
if(it == secoundIterator){
usePosition += seperationOffset;
}
result.addAttributes(it.getAttributes(), usePosition, usePosition+1);
resultCharacter = resultIterator.next();
it.next();
truePosition ++;
}
}
private static AttributedCharacterIterator getIterator(AttributedCharacterIterator firstIterator, AttributedCharacterIterator secoundIterator){
if(firstIterator.current() != CharacterIterator.DONE){
return firstIterator;
}
if(secoundIterator.current() != CharacterIterator.DONE){
return secoundIterator;
}
return null;
}
public static String getString(AttributedString attributedString){
AttributedCharacterIterator it = attributedString.getIterator();
StringBuilder stringBuilder = new StringBuilder();
char ch = it.current();
while( ch != CharacterIterator.DONE)
{
stringBuilder.append( ch);
ch = it.next();
}
return stringBuilder.toString();
}
}