I found the solution to this myself.
You can calculate the width that the string will have after being drawn on the canvas. Then you know where too continue to paint text to the canvas after having changed color.
package com.example;
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
public SampleView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
String blackText = "black";
String redText = " red";
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(30);
mPaint.setTypeface(Typeface.create(Typeface.SERIF,
Typeface.ITALIC));
float canvasWidth = canvas.getWidth();
float blackTextWidth = mPaint.measureText(blackText);
float sentenceWidth = mPaint.measureText(blackText + redText);
float startPositionX = (canvasWidth - sentenceWidth) / 2;
mPaint.setTextAlign(Paint.Align.LEFT);
canvas.translate(0, 80);
mPaint.setColor(Color.BLACK);
canvas.drawText(blackText, startPositionX, 0, mPaint);
mPaint.setColor(Color.RED);
canvas.drawText(redText, startPositionX + blackTextWidth, 0,mPaint);
}
}
}