269

How (if possible) could I set a custom font in a ActionBar title text(only - not the tab text) with a font in my assets folder? I don't want to use the android:logo option.

vidstige
  • 12,492
  • 9
  • 66
  • 110

17 Answers17

425

You can do this using a custom TypefaceSpan class. It's superior to the customView approach indicated above because it doesn't break when using other Action Bar elements like expanding action views.

The use of such a class would look something like this:

SpannableString s = new SpannableString("My Title");
s.setSpan(new TypefaceSpan(this, "MyTypeface.otf"), 0, s.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

// Update the action bar title with the TypefaceSpan instance
ActionBar actionBar = getActionBar();
actionBar.setTitle(s);

The custom TypefaceSpan class is passed your Activity context and the name of a typeface in your assets/fonts directory. It loads the file and caches a new Typeface instance in memory. The complete implementation of TypefaceSpan is surprisingly simple:

/**
 * Style a {@link Spannable} with a custom {@link Typeface}.
 * 
 * @author Tristan Waddington
 */
public class TypefaceSpan extends MetricAffectingSpan {
      /** An <code>LruCache</code> for previously loaded typefaces. */
    private static LruCache<String, Typeface> sTypefaceCache =
            new LruCache<String, Typeface>(12);

    private Typeface mTypeface;

    /**
     * Load the {@link Typeface} and apply to a {@link Spannable}.
     */
    public TypefaceSpan(Context context, String typefaceName) {
        mTypeface = sTypefaceCache.get(typefaceName);

        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                    .getAssets(), String.format("fonts/%s", typefaceName));

            // Cache the loaded Typeface
            sTypefaceCache.put(typefaceName, mTypeface);
        }
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
}

Simply copy the above class into your project and implement it in your activity's onCreate method as shown above.

twaddington
  • 11,607
  • 5
  • 35
  • 46
  • 20
    Nice answer. Whats good to see is that you have also shown a way to cache the typeface element. – Anand Sainath Mar 23 '13 at 07:56
  • 6
    This is excellent. One gotcha - if the `textAllCaps` attribute is set to true on the underlying TextView (e.g. via a theme), then the custom font won't appear. This was an issue for me when I applied this technique to the action bar tab items. – James Oct 18 '13 at 03:47
  • 5
    Note that this implementation of the class assumes that you put your font files in `assets/fonts/`. If you just throw the .ttf/.otf files under assets and not in a subfolder, you should modify the following line of code accordingly: `String.format("fonts/%s", typefaceName)`. I lost good 10 minutes trying to figure it out. If you don't, you will get `java.lang.RuntimeException: Unable to start activity ComponentInfo{com.your.pckage}: java.lang.RuntimeException: native typeface cannot be made` – Dzhuneyt Dec 15 '13 at 13:00
  • 1
    In the moment of starting the app, the default title style is visible and about 1 sec later the custom style appears. Bad UI... – DarkLeafyGreen Dec 18 '13 at 18:20
  • @artworkad that's because your activity's theme is being applied to the `DecorView` before your code has spun up. You can work around this by hiding the action bar in your theme, then show it as your activity is being created. – twaddington Dec 19 '13 at 07:24
  • @twaddington ok, good catch. It would be the perfect solution if we could load the title string from the activity definition in the manifest – DarkLeafyGreen Dec 19 '13 at 07:55
  • This solution is simple, yet it is full of problems and flaws, for example orientation changes. You cannot pass on any CharSequences in Bundles, thus you have to manage it all by yourself. You have to make sure that whatever happens, the same title (and sub title if you use them!) reappear exactly as before. Not always easy!! – Zordid Jan 31 '14 at 16:19
  • @Zordid I'm not sure what you're doing, but so long as you set your ActionBar title in onCreate you shouldn't have any issues. – twaddington Jan 31 '14 at 18:08
  • @twaddington My title changes, triggered from Fragments and their contents. "Normal" titles survive, because the action bar saves its current contents - but only as a String. Any other non-parcelable objects should never be brought from one instance of an Activity to another, thus the TypefaceSpan will be lost after orientation change... – Zordid Feb 10 '14 at 16:20
  • 1
    @Zordid the solution is to simply reapply your title when your activity restarts based on which Fragment is visible. – twaddington Feb 10 '14 at 18:56
  • Where is the try-catch block implemented in https://gist.github.com/twaddington/8035951 – Rohit Tigga Jul 01 '14 at 01:36
  • How to "Hide the action bar in your theme, then show it as your activity is being created" ? – Rohit Tigga Aug 30 '14 at 14:23
  • This solution changed the font for a second and then the font went back to what it was before, when I added a fragment – Kaloyan Roussev Oct 28 '14 at 14:32
  • @J.K. is the fragment calling `setTitle`? It may be overriding the toolbar title. – twaddington Nov 29 '14 at 06:23
  • 2
    This is a great answer and helped me out a ton. One improvement I would add would be to move the caching mechanism into its own class outside of TypefaceSpan. I ran into other situations where I was using a Typeface without a span and this allowed me to take advantage of the cache in those situations as well. – Justin Jun 09 '15 at 14:58
  • @twaddington nice answer! but i have a tiny problem; it stands a little bit upper than what it was before. Is there any solution? – Smile Dec 04 '15 at 16:53
216

I agree that this isn't completely supported, but here's what I did. You can use a custom view for your action bar (it will display between your icon and your action items). I'm using a custom view and I have the native title disabled. All of my activities inherit from a single activity, which has this code in onCreate:

this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);

LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);

//if you need to customize anything else about the text, do it here.
//I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());

//assign the view to the actionbar
this.getActionBar().setCustomView(v);

And my layout xml (R.layout.titleview in the code above) looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

<com.your.package.CustomTextView
        android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp"
            android:maxLines="1"
            android:ellipsize="end"
            android:text="" />
</RelativeLayout>
Kirill Kulakov
  • 10,035
  • 9
  • 50
  • 67
Sam Dozor
  • 40,335
  • 6
  • 42
  • 42
  • 1
    This works fine for the title but if you want a title and tabs it places the custom view to the right of the tabs not left like the title would be. I would love to be able to alter the actual title. – draksia Feb 02 '12 at 16:11
  • 2
    Great solution. If you need a custom text view class that allows specification of the font in XML, please try mine! http://github.com/tom-dignan/nifty -- it's very easy. – Thomas Dignan May 18 '12 at 09:32
  • Does this code have to be in onCreate()? I need to set it dynamically outside of my activity... – IgorGanapolsky Jun 20 '13 at 16:40
  • you need to change the font dynamically? or are you just looking to change the title once the font is already customized? – Sam Dozor Jun 20 '13 at 16:43
  • I don't see any reference to any font in this solution. – AlikElzin-kilaka Aug 02 '13 at 10:45
  • as I mentioned in the answer, I subclassed TextView and used that class in my layout above. In my custom TextView, I override setTypeface, like in this answer: http://stackoverflow.com/questions/8954484/custom-fonts-and-custom-textview-on-android – Sam Dozor Aug 02 '13 at 18:13
  • 2
    This works, but it is way to much work. Plus: you lose some features of the standard title, like having it highlighted when the icon is clicked... Custom titles are not meant to be used to re-create the standard title layout only to change the fonts... – Zordid Feb 03 '14 at 07:33
  • @SamDozor whats `CustomTextView` class to use this sample? –  Nov 14 '14 at 07:17
  • @andbee here's an example: http://stackoverflow.com/questions/2376250/custom-fonts-and-xml-layouts-android, alternatively you could also just call `setTypeface` on a regular `TextView` from within your `Activity`. – Sam Dozor Nov 19 '14 at 15:50
153
int titleId = getResources().getIdentifier("action_bar_title", "id",
            "android");
    TextView yourTextView = (TextView) findViewById(titleId);
    yourTextView.setTextColor(getResources().getColor(R.color.black));
    yourTextView.setTypeface(face);
Digit
  • 1,929
  • 1
  • 14
  • 17
42

From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!

Follow these steps to change the font of Toolbar Title:

  1. Read Downloadable Fonts & select any font from the list (my recommendation) or load a custom font to res > font as per Fonts in XML
  2. In res > values > styles, paste the following (use your imagination here!)

    <style name="TitleBarTextAppearance" parent="android:TextAppearance">
        <item name="android:fontFamily">@font/your_desired_font</item>
        <item name="android:textSize">23sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@android:color/white</item>
    </style>
    
  3. Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont" as shown below

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:titleTextAppearance="@style/TitleBarTextAppearance"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>
    
  4. Enjoy Custom Actionbar Title font styling!!

Mohammed Mukhtar
  • 1,731
  • 20
  • 18
14

The Calligraphy library let's you set a custom font through the app theme, which would also apply to the action bar.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
</style>

<style name="AppTheme.Widget"/>

<style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
   <item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
</style>

All it takes to activate Calligraphy is attaching it to your Activity context:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}

The default custom attribute is fontPath, but you may provide your own custom attribute for the path by initializing it in your Application class with CalligraphyConfig.Builder. Usage of android:fontFamily has been discouraged.

saiyancoder
  • 1,285
  • 2
  • 13
  • 20
thoutbeckers
  • 2,599
  • 22
  • 24
11
    ActionBar actionBar = getSupportActionBar();
    TextView tv = new TextView(getApplicationContext());
    Typeface typeface = ResourcesCompat.getFont(this, R.font.monotype_corsiva);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
            RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
    tv.setLayoutParams(lp);
    tv.setText("Your Text"); // ActionBar title text
    tv.setTextSize(25);
    tv.setTextColor(Color.WHITE);
    tv.setTypeface(typeface, typeface.ITALIC);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setCustomView(tv);
Developer 2
  • 240
  • 1
  • 3
  • 8
  • Great **This is working perfectly** how can I get this app bar into the center? – FGH Apr 12 '20 at 18:54
  • 1
    working like a charm .. just replace `typeface.ITALIC` with `Typeface.ITALIC` to have no static member warning – Zain May 27 '20 at 23:56
  • 1
    05/02/2021 **THE ONLY WORKING SOLUTION FOR ME**. Thanks man. – GLHF May 02 '21 at 11:09
10

It's an ugly hack but you can do it like this (since action_bar_title is hidden) :

    try {
        Integer titleId = (Integer) Class.forName("com.android.internal.R$id")
                .getField("action_bar_title").get(null);
        TextView title = (TextView) getWindow().findViewById(titleId);
        // check for null and manipulate the title as see fit
    } catch (Exception e) {
        Log.e(TAG, "Failed to obtain action bar title reference");
    }

This code is for post-GINGERBREAD devices but this can be easily extended to work with actionbar Sherlock as well

P.S. Based on @pjv comment there's a better way to find action bar title id

final int titleId = 
    Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
Bostone
  • 36,858
  • 39
  • 167
  • 227
  • 4
    I prefer dtmilano's answer in http://stackoverflow.com/questions/10779037/set-activity-title-ellipse-to-middle. It's similar but slightly more future proof. – pjv Jan 10 '13 at 15:44
  • 1
    @pjv - agreed. Seems less "hacky". I modified my answer – Bostone Jan 10 '13 at 16:00
  • 1
    So the question is about custom font. This answers _how to get the text view of the default actionbar_. – AlikElzin-kilaka Aug 02 '13 at 10:42
  • @kilaka - the idea was that if you get the text view setting the custom font would be trivial. This is an old post though, I think twaddington answer is much preferred – Bostone Aug 09 '13 at 17:03
8

Following code will work for all the versions. I did checked this in a device with gingerbread as well as on JellyBean device

 private void actionBarIdForAll()
    {
        int titleId = 0;

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
        {
            titleId = getResources().getIdentifier("action_bar_title", "id", "android");
        }
        else
        {
          // This is the id is from your app's generated R class when ActionBarActivity is used for SupportActionBar

            titleId = R.id.action_bar_title;
        }

        if(titleId>0)
        {
            // Do whatever you want ? It will work for all the versions.

            // 1. Customize your fonts
            // 2. Infact, customize your whole title TextView

            TextView titleView = (TextView)findViewById(titleId);
            titleView.setText("RedoApp");
            titleView.setTextColor(Color.CYAN);
        }
    }
Napolean
  • 5,303
  • 2
  • 29
  • 35
  • This works for me on both ActionBar and the AppCompat ActionBar. But the latter only works if I try to find the title view after onCreate(), so for example placing it to onPostCreate() does the trick. – Harri Jun 04 '14 at 06:45
8

use new toolbar in support library design your actionbar as your own or use below code

Inflating Textview is not an good option try Spannable String builder

Typeface font2 = Typeface.createFromAsset(getAssets(), "fonts/<your font in assets folder>");   
SpannableStringBuilder SS = new SpannableStringBuilder("MY Actionbar Tittle");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, SS.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
actionBar.setTitle(ss);

copy below class

public class CustomTypefaceSpan extends TypefaceSpan{

    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }

        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(tf);
    }

}
Jinu
  • 8,665
  • 4
  • 32
  • 37
3

If you want to set typeface to all the TextViews in the entire Activity you can use something like this:

public static void setTypefaceToAll(Activity activity)
{
    View view = activity.findViewById(android.R.id.content).getRootView();
    setTypefaceToAll(view);
}

public static void setTypefaceToAll(View view)
{
    if (view instanceof ViewGroup)
    {
        ViewGroup g = (ViewGroup) view;
        int count = g.getChildCount();
        for (int i = 0; i < count; i++)
            setTypefaceToAll(g.getChildAt(i));
    }
    else if (view instanceof TextView)
    {
        TextView tv = (TextView) view;
        setTypeface(tv);
    }
}

public static void setTypeface(TextView tv)
{
    TypefaceCache.setFont(tv, TypefaceCache.FONT_KOODAK);
}

And the TypefaceCache:

import java.util.TreeMap;

import android.graphics.Typeface;
import android.widget.TextView;

public class TypefaceCache {

    //Font names from asset:
    public static final String FONT_ROBOTO_REGULAR = "fonts/Roboto-Regular.ttf";
    public static final String FONT_KOODAK = "fonts/Koodak.ttf";

    private static TreeMap<String, Typeface> fontCache = new TreeMap<String, Typeface>();

    public static Typeface getFont(String fontName) {
        Typeface tf = fontCache.get(fontName);
        if(tf == null) {
            try {
                tf = Typeface.createFromAsset(MyApplication.getAppContext().getAssets(), fontName);
            }
            catch (Exception e) {
                return null;
            }
            fontCache.put(fontName, tf);
        }
        return tf;
    }

    public static void setFont(TextView tv, String fontName)
    {
        tv.setTypeface(getFont(fontName));
    }
}
user2136334
  • 648
  • 7
  • 16
3

I just did the following inside the onCreate() function:

TypefaceSpan typefaceSpan = new TypefaceSpan("font_to_be_used");
SpannableString str = new SpannableString("toolbar_text");
str.setSpan(typefaceSpan,0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
getSupportActionBar().setTitle(str);

I am using the Support Libraries, if you are not using them I guess you should switch to getActionBar() instead of getSupportActionBar().

In Android Studio 3 you can add custom fonts following this instructions https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html and then use your newly added font in "font_to_be_used"

Seven
  • 3,232
  • 1
  • 17
  • 15
2

No custom textview is required!

First, disable the title in the toobar in your java code : getSupportActionBar().setDisplayShowTitleEnabled(false);

Then, simply add a TextView inside the toolbar :

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="18sp"
        android:fontFamily="@font/roboto" />

    </android.support.v7.widget.Toolbar>
sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
Apurva Thorat
  • 641
  • 5
  • 10
2

Try using This

TextView headerText= new TextView(getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
headerText.setLayoutParams(lp);
headerText.setText("Welcome!");
headerText.setTextSize(20);
headerText.setTextColor(Color.parseColor("#FFFFFF"));
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/wesfy_regular.ttf");
headerText.setTypeface(tf);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(headerText);
GreenROBO
  • 4,725
  • 4
  • 23
  • 43
Asendo
  • 158
  • 1
  • 10
1

To add to @Sam_D's answer, I had to do this to make it work:

this.setTitle("my title!");
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
TextView title = ((TextView)v.findViewById(R.id.title));
title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
title.setMarqueeRepeatLimit(1);
// in order to start strolling, it has to be focusable and focused
title.setFocusable(true);
title.setSingleLine(true);
title.setFocusableInTouchMode(true);
title.requestFocus();

It seems like overkill - referencing v.findViewById(R.id.title)) twice - but that's the only way it would let me do it.

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
1

To update the correct answer.

firstly : set the title to false, because we are using custom view

    actionBar.setDisplayShowTitleEnabled(false);

secondly : create titleview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@android:color/transparent" >

    <TextView
       android:id="@+id/title"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerVertical="true"
       android:layout_marginLeft="10dp"
       android:textSize="20dp"
       android:maxLines="1"
       android:ellipsize="end"
       android:text="" />

</RelativeLayout>

Lastly :

//font file must be in the phone db so you have to create download file code
//check the code on the bottom part of the download file code.

   TypeFace font = Typeface.createFromFile("/storage/emulated/0/Android/data/"   
    + BuildConfig.APPLICATION_ID + "/files/" + "font name" + ".ttf");

    if(font != null) {
        LayoutInflater inflator = LayoutInflater.from(this);
        View v = inflator.inflate(R.layout.titleview, null);
        TextView titleTv = ((TextView) v.findViewById(R.id.title));
        titleTv.setText(title);
        titleTv.setTypeface(font);
        actionBar.setCustomView(v);
    } else {
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("  " + title); // Need to add a title
    }

DOWNLOAD FONT FILE : because i am storing the file into cloudinary so I have link on it to download it.

/**downloadFile*/
public void downloadFile(){
    String DownloadUrl = //url here
    File file = new File("/storage/emulated/0/Android/data/" + BuildConfig.APPLICATION_ID + "/files/");
    File[] list = file.listFiles();
    if(list == null || list.length <= 0) {
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try{
                    showContentFragment(false);
                } catch (Exception e){
                }
            }
        };

        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
        request.setVisibleInDownloadsUi(false);
        request.setDestinationInExternalFilesDir(this, null, ModelManager.getInstance().getCurrentApp().getRegular_font_name() + ".ttf");
        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
    } else {
        for (File files : list) {
            if (!files.getName().equals("font_name" + ".ttf")) {
                BroadcastReceiver onComplete = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        try{
                            showContentFragment(false);
                        } catch (Exception e){
                        }
                    }
                };

                registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
                request.setVisibleInDownloadsUi(false);
                request.setDestinationInExternalFilesDir(this, null, "font_name" + ".ttf");
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            } else {
                showContentFragment(false);
                break;
            }
        }
    }
}
0

We need to use reflections for achieving this

final int titleId = activity.getResources().getIdentifier("action_bar_title", "id", "android");

    final TextView title;
    if (activity.findViewById(titleId) != null) {
        title = (TextView) activity.findViewById(titleId);
        title.setTextColor(Color.BLACK);
        title.setTextColor(configs().getColor(ColorKey.GENERAL_TEXT));
        title.setTypeface(configs().getTypeface());
    } else {
        try {
            Field f = bar.getClass().getDeclaredField("mTitleTextView");
            f.setAccessible(true);
            title = (TextView) f.get(bar);
            title.setTextColor(Color.BLACK);
            title.setTypeface(configs().getTypeface());
        } catch (NoSuchFieldException e) {
        } catch (IllegalAccessException e) {
        }
    }
Jiju Induchoodan
  • 4,236
  • 1
  • 22
  • 24
-1

TRY THIS

public void findAndSetFont(){
        getActionBar().setTitle("SOME TEST TEXT");
        scanForTextViewWithText(this,"SOME TEST TEXT",new SearchTextViewInterface(){

            @Override
            public void found(TextView title) {

            } 
        });
    }

public static void scanForTextViewWithText(Activity activity,String searchText, SearchTextViewInterface searchTextViewInterface){
    if(activity == null|| searchText == null || searchTextViewInterface == null)
        return;
    View view = activity.findViewById(android.R.id.content).getRootView();
    searchForTextViewWithTitle(view, searchText, searchTextViewInterface);
}

private static void searchForTextViewWithTitle(View view, String searchText, SearchTextViewInterface searchTextViewInterface)
{
    if (view instanceof ViewGroup)
    {
        ViewGroup g = (ViewGroup) view;
        int count = g.getChildCount();
        for (int i = 0; i < count; i++)
            searchForTextViewWithTitle(g.getChildAt(i), searchText, searchTextViewInterface);
    }
    else if (view instanceof TextView)
    {
        TextView textView = (TextView) view;
        if(textView.getText().toString().equals(searchText))
            if(searchTextViewInterface!=null)
                searchTextViewInterface.found(textView);
    }
}
public interface SearchTextViewInterface {
    void found(TextView title);
}
user2212515
  • 1,220
  • 1
  • 12
  • 10