首页 > 解决方案 > 如何从相邻文本中获取文本颜色

问题描述

我正在开发一个 android 应用程序,在该应用程序中,我可以使用可扩展的字符串将不同的颜色应用于 edittext 的文本,并通过 ActivityResult 获取颜色,它工作得很好,但是当我开始输入更多文本时,它会得到默认颜色,即黑色。请注意,我只使用了一个编辑文本。现在我想添加一个功能,可以在选择颜色后输入颜色。另外,我想要另一个功能,当单击另一种颜色的文本附近时,它会自动获取该文本颜色,并且当一个人开始键入时,它会输入该颜色。意思是我想从相邻的文本颜色中获取颜色。我尝试了以下方法,但它为我的整个文本着色。我不希望我的整个文本获得相同的颜色。

text.setTextColor(Color.parseColor(color));

这是我的可扩展字符串颜色编码,它工作正常。

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RequestCode && resultCode == RESULT_OK && data != null) {
        color = data.getStringExtra("color");
        texto.setTextColor(Color.parseColor(color));
    }
    Spannable str = texto.getText();
    int selStart = texto.getSelectionStart();
    int selEnd = texto.getSelectionEnd();
    ForegroundColorSpan[] styleSpans = texto.getText().getSpans(selStart, selEnd, ForegroundColorSpan.class);

    if (styleSpans.length > 0) {
        int lastSpanEnd = 0;
        for (ForegroundColorSpan styleSpan : styleSpans) {
            int oldStyle = styleSpan.getForegroundColor();
            int spanStart = str.getSpanStart(styleSpan);
            int spanEnd = str.getSpanEnd(styleSpan);
            str.removeSpan(styleSpan);
            if (spanStart < selStart) {
                str.setSpan(new ForegroundColorSpan(oldStyle), spanStart, selStart, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            if (spanEnd > selEnd) {
                str.setSpan(new ForegroundColorSpan(oldStyle), selEnd, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        if (selEnd != lastSpanEnd) {
            str.setSpan(new ForegroundColorSpan(Color.parseColor(color)), selStart, selEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    else {
        str.setSpan(new ForegroundColorSpan(Color.parseColor(color)), selStart, selEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

标签: javaandroidtextcolor

解决方案


推荐阅读