如何为Android中的edittext编写的每个字符设置不同的颜色?

时间:2016-07-28 14:28:53

标签: java android android-edittext

我正在尝试用begin # Document insert code rescue Mongo::Error => e if e.message.include? 'E11000' # Change the id of the hash & re-try to insert it end end 用不同颜色着色的字符。 例如,我希望在edittext中写入“a”为红色,而其他时间保持黑色。至少可能吗?

我在edittext中找到了一些关于颜色设置的答案,如下所示,但是它的全部是关于起始索引和结束索引范围的颜色设置。

**示例**

edittext

2 个答案:

答案 0 :(得分:1)

是的,但是我不知道在性能方面是否过于昂贵。 您可以使用TextWatcher为您在char-color的Map上插入的最后一个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);
    }
}

这是结果

enter image description here

答案 1 :(得分:0)

一种方法是使用Html.fromHtml(String)并使用Map将预设颜色设置为字体颜色。 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 + "]]>");
}

然后使用它,你可以做类似的事情:

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