Java – How to programmatically change the color of toolbar text

How to programmatically change the color of toolbar text… here is a solution to the problem.

How to programmatically change the color of toolbar text

My toolbar title needs to be able to change color based on button clicks. For example, the default color of the toolbar title is white, but if I press a button, I want it to turn red.

I tried the following method:

SpannableString title;
title.setSpan(new ForegroundColorSpan(Color.argb(1, 255, 64, 129)), 0, remainingTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

But for some reason, the colors just don’t want to change. It used to work with ActionBar, but for some reason the same approach doesn’t work for toolbars.

Solution

You can use it like this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Hello");
toolbar.setTitleTextColor(Color.RED);//for red colored toolbar title

Related Problems and Solutions