1

Ich möchte meinen Toolbar-Titel auf "Videos (4)" setzen, wobei der Teil "Videos" eine Farbe hat und der Teil "(4)" eine andere Farbe ist. Ich möchte Farben aus meiner colors.xml Ressourcendatei verwenden.Mehrere Farben im Toolbar-Titel?

Wie kann ich das tun?

Hier ist, wie ich die Toolbar Titel habe die Einrichtung:

getSupportActionBar().setTitle("Videos (" + numVideos + ")"); 

Antwort

2

können Sie einstellen, benutzerdefinierte Schriftart und Farben mit spannable.

Try this:

protected void setActionBarTitle(String title) { 
    //if API level below 18, there is a bug at Samsung and LG devices 
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { 
     getSupportActionBar().setTitle(title); 
    } else { 
     SpannableString s = new SpannableString(title); 
     s.setSpan(new TypefaceSpan(this, "Your-Font.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     getSupportActionBar().setTitle(s); 
    } 


} 

In Ihrem Fall das funktionieren sollte:

SpannableString firstPart = new SpannableString("Videos "); 
SpannableString lastPart = new SpannableString(" (4)"); 

firstPart.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getApplicationContext(), R.color.white)), 0, firstPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

lastPart.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getApplicationContext(), R.color.black)), 0, lastPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

dann stellen Sie Ihren Titel thike dies:

getSupportActionBar().setTitle(firstPart + lastPart); 

oder wie folgt aus:

getSupportActionBar().setTitle(TextUtils.concat(firstPart, lastPart)); 
+0

Dies erklärt nicht, wie mehrere Farben in einem einzigen Toolbar-Titel verwendet werden. Ich möchte auch nicht die Schriftart ändern. – user486123

+0

@ user486123 Zuerst sagte ich dir die Logik dahinter. Just updated meine Antwort/ –

+0

Hatte 'TextUtils.concat (firstPart, lastPart)' anstelle von 'firstPart + lastPart' zu verwenden, aber danke! – user486123

0
String text = "<font color=#cc0029>Videos</font> <font color=#ffcc00>(" + numVideos + ")</font>"; 

getSupportActionBar().setTitle(Html.fromHtml(text)); 

+0

"Ich möchte Farben aus meiner' colors.xml'-Ressourcendatei verwenden. " – user486123

+0

In diesem Fall erwähnen Sie direkt die Farbe innerhalb der Schriftart-Tag – sasikumar

Verwandte Themen