我有一个简单的文本编辑器应用程序,用户可以在EditText中选择单词并更改其颜色。 要更改所选单词的颜色,我使用以下代码:
EditText edtText = (EditText) findViewById(R.id.edtText);
SpannableStringBuilder sb = new SpannableStringBuilder(edtText.getText().toString());
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
sb.setSpan(fcs, edtText.getSelectionStart(), edtText.getSelectionEnd(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
edtText.setText(sb);
此代码可以正常工作,但我无法设置多种颜色来编辑文本。例如,我写了#34;你好,你好吗?"在EditText中,我想要着色"你好"蓝色和"你好吗?"变红了。当我选择"你好"并将其涂成蓝色,然后我选择"你好吗"并将它染成红色,"你好"这个词会是黑色的。有谁能够帮我? tahnks
答案 0 :(得分:0)
您需要使用HTML格式:
EditText.setText(Html.fromHtml(htmlformatString))
答案 1 :(得分:0)
@ user2139223:是的它是正确的,但在我的应用程序中,用户在编辑文本中编写一个语句并可以更改它的颜色。我不知道什么是陈述和选择哪个词。我的问题是,用类似的词语,因为选择其中一个和颜色,所有这些都是颜色。 这是我的代码:
private void colorText(){
EditText edtText = (EditText) findViewById(R.id.edtText);
String allText = Html.toHtml(edtText.getText());
String selectedText = edtText.getText().toString().substring(edtText.getSelectionStart(), edtText.getSelectionEnd());
String color = "#ff0000";
String colorText = "<font color=\"" + color + "\">" + selectedText + "</font>";
String text =allText.replace(selectedText, colorText);
edtText.setText(Html.fromHtml(text));
}
单击按钮,我调用此方法并将所选单词的颜色更改为红色。