我有EditText和3个颜色选择框。我想选择一种颜色,然后开始在EditText中键入文本。目前,我只能编写文本,选择它然后更改文本的颜色。
我试过以下但没有工作:
将ForegroundColorSpan范围设置为Spannable.SPAN_INCLUSIVE_INCLUSIVE
中的TextWatcher
和onCheckedChanged
为每个角色添加跨度
删除所有跨度,然后再添加新的
我还试图打印所有跨度的颜色,看起来跨度正确添加,但EditText没有按照这些跨度显示颜色。例如:
char = 0 (T)
span 0 = Green
span 1 = Green
char = 1 (E)
span 0 = Green
span 1 = Green
char = 1 (S)
span 0 = Green
span 1 = Red
char = 2 (T)
span 0 = Green
span 1 = Red
Output: EditText shows "TEST" in all green color
Note: selecting the text and applying span shows correct colors in EditText
- >布局/ activity.xml
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine|textNoSuggestions" />
- &GT; MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
.......
mEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
spannable.setSpan(new ForegroundColorSpan(selectedColor), i, i, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Spannable spannable = this.mEditText.getText();
int selStart = this.mEditText.getSelectionStart();
int selEnd = this.mEditText.getSelectionEnd();
if(group.getId() == R.id.radioGroupColor) {
int selected = 0;
switch (checkedId) {
case R.id.radioGreen:
selected = Color.GREEN;
break;
case R.id.radioRed:
selected = Color.RED;
break;
case R.id.radioBlue:
selected = Color.BLUE;
break;
}
if(selStart == selEnd) {
// There is no selection
} else {
spannable.setSpan(new ForegroundColorSpan(selected), selStart, selEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
}
}
答案 0 :(得分:0)
在EditText
中键入文本之前设置文本颜色
良好做法,我建议您使用TextWatcher
。您应该覆盖 onTextChanged
方法。
onTextChanged
(CharSequence s,int start,int before,int count) - 调用此方法是为了在s内通知您计数 从开头开始的字符刚刚替换了旧文本 之前的长度。
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Your Work
}