Search code examples
androidtextviewwidgetandroid-widgetstrikethrough

Strike through substring of text in Android widget


I have a text view in my android widget and I need to strike through only certain lines of text. I found this in another SO question to strike through text in a widget:

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);

The problem is this strikes through all text in the text view. How can I strike through only part of the text view's text?


Solution

  • Xoce's answer is pretty much right but it was more of a general answer for in app textviews, but with some tweaking I have the way to do it for widgets. (Also thanks to CommonsWare for pushing me in the right direction.

    In the updateAppWidget method, you can add text to the textview using remote views. To customize substrings of the textview's text with a strike through, use a spannable string builder (you can also use differnt spans to achieve bold, underline, italic, etc.)

    Here's what I did:

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {
        CharSequence widgetText = NewAppWidgetConfigureActivity.loadTitlePref(context, appWidgetId, NewAppWidgetConfigureActivity.TEXT_KEY);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
    
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(widgetText);
        StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
    
        spannableStringBuilder.setSpan(strikethroughSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        views.setTextViewText(R.id.appwidget_text, spannableStringBuilder);
    
        ...
    
    }