How to set different colors for each characters written in edittext in Android?

耗尽温柔 提交于 2020-12-06 16:00:28

问题


I am trying make characters written in edittext colored with a different color. For example, I want to have 'a' in red all the time when it is written in edittext, while the others stay in black. Is it possible at least?

I found some answers regarding color-setting in edittext as below, however it is all about color-setting by the range of start index and end index.

** example **

final String text = "for example";
Spannable modifiedText = new SpannableString(text);
modifiedText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red)), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(modifiedText);

回答1:


Yes it's possible, but I don't know if is too expensive in terms of performance. You can use a TextWatcher to color you last char inserted base on your Map of char-color.

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);
    }
}

This is the result




回答2:


One way would be to use Html.fromHtml(String) and set the font colors through that using a Map to your predefined colors. e.g.

private static final String FONT_REPLACEMENT = "<font color='%1$s'>%2$s</font>";
private static final String DEFAULT_COLOR = "#FAFAFA";

public Spanned convertToHtml(String text, Map<String, String> colorSets){
    String altered = "<![CDATA[";

    for(int i = 0; i < text.length(); i++) {
        String value = String.valueOf(text.charAt(i));
        String color = colorSets.get(value.toLowerCase(Locale.US));

        if(color == null)
            color = DEFAULT_COLOR;

        altered += String.format(FONT_REPLACEMENT, color, value);
    }

    return Html.fromHtml(altered + "]]>");
}

And then to use it, you could do something like:

Map<String, String> colors = new HashMap<String, String();
colors.put("a", "#FF0000");
colors.put("b", "#00FF00");
colors.put("c", "#0000FF");
....

textView.setText(convertToHtml("for example", colors));


来源:https://stackoverflow.com/questions/38639325/how-to-set-different-colors-for-each-characters-written-in-edittext-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!