如何让用户突出显示TextView

时间:2017-02-06 10:15:41

标签: java android android-layout

我正在为学生开发一个带有一些TextViews的Android项目,但是我希望用户长按并获得选项,以不同的颜色突出显示内容的某些部分,就像在某些圣经应用程序或Adobe Reader中一样。长按可以选择标记文本颜色。 我会感谢任何指导这项工作。

1 个答案:

答案 0 :(得分:0)

使用Spannable字符串来设置测试样式 示例:

String firstWord = "Hello";
String secondWord = "World!";

TextView tvHelloWorld = (TextView)findViewById(R.id.tvHelloWorld);

// Create a span that will make the text red
ForegroundColorSpan redForegroundColorSpan = new ForegroundColorSpan(
        getResources().getColor(android.R.color.holo_red_dark));

// Use a SpannableStringBuilder so that both the text and the spans are mutable
SpannableStringBuilder ssb = new SpannableStringBuilder(firstWord);

// Apply the color span
ssb.setSpan(
        redForegroundColorSpan,            // the span to add
        0,                                 // the start of the span (inclusive)
        ssb.length(),                      // the end of the span (exclusive)
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // behavior when text is later inserted into the SpannableStringBuilder
                                           // SPAN_EXCLUSIVE_EXCLUSIVE means to not extend the span when additional
                                           // text is added in later

// Add a blank space
ssb.append(" ");

// Create a span that will strikethrough the text
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();

// Add the secondWord and apply the strikethrough span to only the second word
ssb.append(secondWord);
ssb.setSpan(
        strikethroughSpan,
        ssb.length() - secondWord.length(),
        ssb.length(),
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Set the TextView text and denote that it is Editable
// since it's a SpannableStringBuilder
tvHelloWorld.setText(ssb, TextView.BufferType.EDITABLE);

enter image description here

来源:https://guides.codepath.com/android/Working-with-the-TextView