在 Android 小部件中删除文本的子字符串

Mik*_*ang 2 android widget textview android-widget strikethrough

我的 android 小部件中有一个文本视图,我只需要删除某些文本行。我在另一个 SO 问题中发现了这一点,以删除小部件中的文本:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

// strike through text, this strikes through all text
views.setInt(R.id.appwidget_text, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
Run Code Online (Sandbox Code Playgroud)

问题是这会贯穿文本视图中的所有文本。如何仅删除文本视图文本的一部分?

ΦXo*_*a ツ 5

使用SpannableStringBuilderStrikethroughSpan

例如,要获得以下效果,请参阅以下代码段: 在此处输入图片说明


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);
Run Code Online (Sandbox Code Playgroud)

更酷的效果 在这里