android 突出显示文本视图中文本

vddsk6oq  于 2022-12-25  发布在  Android
关注(0)|答案(8)|浏览(172)

我有一个随机背景颜色的文本视图(可以是任何颜色)。我也有一个文本在这个文本视图,需要可读。我认为最好的解决方案是突出显示白色的文本,并设置文本颜色为黑色。
我的问题是:是否可以突出显示XML中texview内部的文本?
我的布局中包含以下内容:

<TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/colorButton4"
        android:layout_gravity="right|bottom"
        android:background="@drawable/layout_border"
        android:layout_marginRight="30dp"
        android:layout_marginBottom ="30dp"
        android:clickable="true"
        android:onClick="onClick"
        android:gravity="center"
        android:textColorHighlight="@color/bgWhite"
        android:textColor="@color/Black"
        android:text="5431354" />

但它没有突出显示文本。

ee7vknir

ee7vknir1#

您可能希望为此使用SpannableString,它允许字符串的各个部分在TextView中以不同的方式呈现。
就像这样:

SpannableString str = new SpannableString("Highlighted. Not highlighted.");
    str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0);
    textView.setText(str);
mcdcgff0

mcdcgff02#

轻松的方式

您可以使用Spannable类设置文本格式。

textView.setText("Hello, I am Awesome, Most Awesome"); // set text first
setHighLightedText(textView, "a"); // highlight all `a` in TextView

输出将类似于下图。

方法是这样的。

/**
     * use this method to highlight a text in TextView
     *
     * @param tv              TextView or Edittext or Button (or derived from TextView)
     * @param textToHighlight Text to highlight
     */
    public void setHighLightedText(TextView tv, String textToHighlight) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToHighlight, 0);
        Spannable wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToHighlight, ofs);
            if (ofe == -1)
                break;
            else {
                // set color here
                wordToSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }

你可以check this answer来点击高亮显示的文本。

qoefvg9y

qoefvg9y3#

要高亮显示所有出现的特定文本,请使用此方法:

private void highlightString(String input) {
//Get the text from text view and create a spannable string
SpannableString spannableString = new SpannableString(mTextView.getText());
//Get the previous spans and remove them
BackgroundColorSpan[] backgroundSpans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class);

for (BackgroundColorSpan span: backgroundSpans) {
    spannableString.removeSpan(span);
}

//Search for all occurrences of the keyword in the string
int indexOfKeyword = spannableString.toString().indexOf(input);

while (indexOfKeyword > 0) {
    //Create a background color span on the keyword
    spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), indexOfKeyword, indexOfKeyword + input.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    //Get the next index of the keyword
    indexOfKeyword = spannableString.toString().indexOf(input, indexOfKeyword + input.length());
}

//Set the final text on TextView
mTextView.setText(spannableString);}

注意:mTextView是一个TextView对象,您希望在其中突出显示文本

imzjd6km

imzjd6km4#

我编写了一个Kotlin方法,它将突出显示String中出现的所有关键字,并返回SpannableString

fun main() {
    textView.text = highlightKeywords(
        highlightColor = ContextCompat.getColor(context, R.color.colorAccent),
        message = "Hello World, and Hello to all my Hello Friends.",
        keywords = listOf("Hello")
    )
}

fun highlightKeywords(
    highlightColor: Int,
    message: String,
    keywords: List<String>,
): SpannableString {
    val spannableString = SpannableString(message)
    keywords.forEach { keyword ->
        if (!keyword.isBlank()) {
            var startIndex = message.indexOf(keyword)

            while (startIndex >= 0) {
                spannableString.setSpan(
                    ForegroundColorSpan(highlightColor),
                    startIndex,
                    startIndex + keyword.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )

                startIndex = message.indexOf(keyword, startIndex + keyword.length)
            }
        }
    }
    return spannableString
}
k7fdbhmy

k7fdbhmy5#

https://github.com/datanapps/HighlightedTextView

<datanapps.highlightedtextview.HighLightTextView
    android:id="@+id/tv2"
    android:layout_below="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers."
    android:textColor="@color/white"
    app:fontFamily="serif"
    android:lineSpacingExtra="50sp"
    android:layout_marginTop="20dp"
    android:textSize="20sp"
    android:textAlignment="viewEnd"
    app:highLightColor="@color/blue"
    />

ej83mcc0

ej83mcc06#

Suraj's answer很好用,但是缺少两个组件:第一,它不会突出显示第一个单词(如Rany注解所示);第二,它不会忽略大小写,因此在此字符串中搜索"test""This is a Test"将找不到任何内容。
这是我更新的答案,它通过一个传递的参数解决了这两个问题,如果你想使用自定义颜色来突出显示,还添加了alpha。注意,重载的第一个方法是一个示例,说明了如何返回前一个方法所做的事情,而不是选择的第一个项目。

/**
     * Use this method to get the same return as the previous method
     */
    public static SpannableString buildHighlightString(String originalText, String textToHighlight){
        return buildHighlightString(originalText, textToHighlight, false, Color.YELLOW, 1.0F);
    }
    
    /**
     * Build a spannable String for use in highlighting text colors
     * 
     * @param originalText The original text that is being highlighted
     * @param textToHighlight The text / query that determines what to highlight
     * @param ignoreCase Whether or not to ignore case. If true, will ignore and "test" will have
     *                   the same return as "TEST". If false, will return an item as highlighted
     *                   only if it matches it case specficic.
     * @param highlightColor The highlight color to use. IE {@link Color#YELLOW} || {@link Color#BLUE}
     * @param colorAlpha Alpha to adjust how transparent the color is. 1.0 means it looks exactly
     *                   as it should normally where as 0.0 means it is completely transparent and
     *                   see-through. 0.5 means it is 50% transparent. Useful for darker colors
     */
    public static SpannableString buildHighlightString(String originalText, String textToHighlight,
                                                       boolean ignoreCase, @ColorInt int highlightColor,
                                                       @FloatRange(from = 0.0, to = 1.0) float colorAlpha){
        SpannableString spannableString = new SpannableString(originalText);
        if (TextUtils.isEmpty(originalText) || TextUtils.isEmpty(textToHighlight)) {
            return spannableString;
        }
        String lowercaseOriginalString = originalText.toLowerCase();
        String lowercaseTextToHighlight = textToHighlight.toLowerCase();
        if(colorAlpha < 1){
            highlightColor = ColorUtils.setAlphaComponent(highlightColor, ((int)(255*colorAlpha)));
        }
        //Get the previous spans and remove them
        BackgroundColorSpan[] backgroundSpans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class);
        for (BackgroundColorSpan span: backgroundSpans) {
            spannableString.removeSpan(span);
        }
        //Search for all occurrences of the keyword in the string
        int indexOfKeyword = (ignoreCase)
                ? lowercaseOriginalString.indexOf(lowercaseTextToHighlight)
                : originalText.indexOf(textToHighlight);
        while (indexOfKeyword != -1) {
            //Create a background color span on the keyword
            spannableString.setSpan(new BackgroundColorSpan(highlightColor), indexOfKeyword,
                    indexOfKeyword + (textToHighlight.length()), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            
            //Get the next index of the keyword
            indexOfKeyword = (ignoreCase)
                    ? lowercaseOriginalString.indexOf(lowercaseTextToHighlight, (indexOfKeyword) + textToHighlight.length())
                    : originalText.indexOf(textToHighlight, (indexOfKeyword) + textToHighlight.length());
        }
        return spannableString;
    }
zdwk9cvp

zdwk9cvp7#

如果您检查了TextView的文档,您会发现android:textColorHighlight并没有实现您想要的功能:https://developer.android.com/reference/android/widget/TextView.html#attr_android:textColorHighlight
它只在选择文本时使用,例如在EditText中。您需要将TextView的背景设置为“突出显示”。

dtcbnfnu

dtcbnfnu8#

在Android上工作了4年之后,我可以有把握地说,没有XML之外的代码是不可能的。如果你能使用一些代码,其他人分享的解决方案将对你有所帮助,所以请阅读!

编辑:我选择了一个新的答案作为有效的,但它需要编码一个自定义的TextView!

相关问题