how to customize use of OnDraw()

152 Views Asked by At

I want to setStrikeThrough of a different color than the textcolor on just 1 word in my Custom textView. How do I do that. At the moment all of my textView gets Strikethrough'd. Here is the code for the Custom TextView Class with just the OnDraw method.

public class CustomTextView extends TextView {

@Override
protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    paint.setColor(color);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrikeThruText(true);
    paint.setStrokeWidth(6.0f);
    paint.setFlags(Paint.ANTI_ALIAS_FLAG);
    super.onDraw(canvas);
    float width = getWidth();
    float height = getHeight();
    canvas.drawLine(0, height / 2, width, height / 2, paint);
}

If I have "Hello World" in my TextView, I just want the "Hello" to have a strikethrough rather than the whole textview to have it. I have been stuck at this for a very long time now any help would be gladly accepted

1

There are 1 best solutions below

0
Perraco On

If you want a strike through for a single word, then would be better to use a StrikethroughSpan, without needing to override the onDraw method or even using a custom TextView at all.

You can define a word character start index, and word character end index, such as next:

final StrikethroughSpan span = new StrikethroughSpan();
final Spannable spannable = (Spannable)yourTextView.getText();
spannable.setSpan(span, WORD_START_INDEX, WORD_END_INDEX, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(spannable);

As a side note, notice that you should never create new class instances inside the onDraw method, such as in your example Paint paint = new Paint(), which you are creating right inside the onDraw call. Lint should already warn you about this. The onDraw method can be called hundreds of times per second, and therefore create hundreds of new instances and filling up the memory. Avoid always to create new class instances inside methods such as onDraw, onMeasure, or any other method that can be called hundreds of times in a short period. Always check the lint warnings (yellow marks).