Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/186.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为TextView中的文本设置不同的颜色_Java_Android_Textview - Fatal编程技术网

Java 为TextView中的文本设置不同的颜色

Java 为TextView中的文本设置不同的颜色,java,android,textview,Java,Android,Textview,我在我的应用程序中放了一个文本视图在片段中。每一页都有不同的文本。我想每次你找到例如“树”这个词时,这个词被涂成红色,其余的词被涂成白色。我怎么做呢?谢谢要更改文本的颜色,请使用: textview.setTextColor(Color.RED) 这将用红色替换所有单词“tree” Pattern pattern = Pattern.compile("tree"); Matcher matcher = pattern.matcher(yourTextViewText); final Span

我在我的应用程序中放了一个文本视图在片段中。每一页都有不同的文本。我想每次你找到例如“树”这个词时,这个词被涂成红色,其余的词被涂成白色。我怎么做呢?谢谢

要更改文本的颜色,请使用:

textview.setTextColor(Color.RED)

这将用红色替换所有单词“tree”

Pattern pattern = Pattern.compile("tree");
Matcher matcher = pattern.matcher(yourTextViewText);

final SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(yourTextViewText);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
while (matcher.find()) {
    spannableBuilder.setSpan(
        span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
yourTextView.setText(spannableBuilder);