Yes, it is possible using one of the Layout classes. These are helper classes for drawing text on canvas, and they support Spannables. If your text does not change, use StaticLayout.
Example
Add this to your own view class.
private StaticLayout layout;
put this code in onLayout or onSizeChanged
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers"); wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); TextPaint paint = new TextPaint(); paint.setTextSize(20f); paint.setColor(Color.RED); layout = new StaticLayout(wordtoSpan, paint, getWidth(), Alignment.ALIGN_NORMAL, 1, 0, false);
Then in your drawing method just call
layout.draw(canvas);
If your text changes frequently, you can use DynamicLayout .
Editable.Factory fac = Editable.Factory.getInstance(); Editable edit = fac.newEditable(wordtoSpan); DynamicLayout layout = new DynamicLayout(edit,paint,getWidth(),Alignment.ALIGN_CENTER,1,0,false);
edit text using an editing object
edit.append("hello");
Renard
source share