我正在做一些事情,我的最终目标是
在TextView中有不同颜色的单词
从用户那里获取输入,并将该单词以特定的颜色放入TextView中
http://puu.sh/9wpuU/fcc558a48a.png
因此,我试图做的是在我的警报生成器中的OK按钮中,取一个SpannableStringBuilder,附加新的用户输入文本,并将其设置为特定的颜色。但是它删除了我以前的所有颜色跨度(我想是因为您一次只能在SpannableStringBuilder中有一个跨度?)有办法绕过这件事吗?这是我试过的。编辑整个类现在在那里
public class WritingScreen extends Activity {
String title;
String text;
String userInput;
TextView story;
SpannableStringBuilder sb;
ForegroundColorSpan fcs;
int colorTracker;
int currentCharCount;
int nextCharCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.writing_screen);
story = (TextView) findViewById(R.id.storyText);
sb = new SpannableStringBuilder(story.getText().toString());
fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
currentCharCount = story.getText().length();
}
public void addTextClick(View v){
final EditText input = new EditText(this);
new AlertDialog.Builder(this)
.setTitle("Input Word")
.setView(input)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
value = " " + value;
sb = new SpannableStringBuilder(story.getText());
sb.append(value);
nextCharCount = sb.length();
sb.setSpan(fcs, currentCharCount, nextCharCount, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
story.setText(sb);
currentCharCount = nextCharCount;
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
}
}这给了我这个
http://puu.sh/9wq7z/7b7fb2f909.jpg
当我连续输入OK jj meh时。首先,我希望他们都保持我给每个单词分配的颜色。有什么想法吗?
发布于 2014-06-16 19:32:34
首先,story.getText().toString()将当前Spannable转换为一个字符串,该字符串将丢失所有标记信息。您应该使用sb.append(story.getText())代替。
其次,您必须在每次创建Span 时创建一个新的 --从setSpan()的代码来看,如果在构建器中已经找到了相同的span,它就会被更改。这可能是您丢失以前格式的原因。
例如:
int[] colors = new int[] { Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW };
ForegroundColorSpan fcs = new ForegroundColorSpan(colors[new Random().nextInt(colors.length)]);
SpannableStringBuilder sb = new SpannableStringBuilder(mTextView.getText());
int currentCharCount = sb.length();
sb.append(mEditText.getText().toString().trim());
int nextCharCount = sb.length();
sb.setSpan(fcs, currentCharCount, nextCharCount, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mTextView.setText(sb);https://stackoverflow.com/questions/24250719
复制相似问题