是的,它是可能的,但我不知道,如果是在性能方面過於昂貴。 您可以使用TextWatcher爲您最後插入的char字符着色,該字符基於您的字符顏色映射。
public class MainActivity extends AppCompatActivity {
private SpannableStringBuilder mSpannableStringBuilder;
private EditText mEditText;
private static final Map<String, Integer> COLORS_MAP = new HashMap<>();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// here you can populate your map with colors
COLORS_MAP.put("a", Color.RED);
COLORS_MAP.put("b", Color.GREEN);
COLORS_MAP.put("c", Color.BLUE);
COLORS_MAP.put("d", Color.MAGENTA);
mSpannableStringBuilder = new SpannableStringBuilder();
mEditText = (EditText) findViewById(R.id.editText);
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
// unregister and register the listener to avoid infinite loop
mEditText.removeTextChangedListener(this);
int start = s.length() - 1;
String lastChar = s.toString().substring(start);
SpannableString lastSpannableChar = new SpannableString(lastChar);
// pick the color based on the last char
int color = pickColorByChar(lastChar);
// Span to set char color
ForegroundColorSpan fcs = new ForegroundColorSpan(color);
// Set the text color for the last character
lastSpannableChar.setSpan(fcs, 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// append the last char to the string builder so you can keep the previous span
mSpannableStringBuilder.append(lastSpannableChar);
mEditText.setText(mSpannableStringBuilder);
mEditText.setSelection(mEditText.getText().length()); //this is to move the cursor position
mEditText.addTextChangedListener(this);
}
}
});
}
public int pickColorByChar(String aChar){
return COLORS_MAP.get(aChar);
}
}
這是結果
是的,它是使用spannable用於內部的TextView着色,得到你需要使用的方法來獲得索引指數的好方法「A」 – Chol
謝謝你的回答。然而,我所尋找的是取決於特定角色的顏色的方式,以便每當鍵入「a」時它就變成紅色。例如,以下示例中只有三個字母爲紅色,超出了其索引。例如)「我有一個蘋果。」 – lifeBalkan
代碼格式 – fantaghirocco