1

Possible Duplicate:
Android - Using Custom Font

What's the best or Efficient way to Customize the font in An Android APPlication? I have been trying to customize my Textviews and Edittexts, but my application is kind of slow because I'm using custom fonts and takes a lot of memory and sometimes even crashes.

Community
  • 1
  • 1
Yauraw Gadav
  • 1,706
  • 1
  • 18
  • 39

1 Answers1

4

I seriously doubt the slowness in your application is a result of you using custom fonts. It's probably the way you're applying them. Typically, I'll do something like the following in my Activity:

//Get an instance to the root of your layout (outermost XML tag in your layout
//document)
ViewGroup root = (ViewGroup)findViewById(R.id.my_root_viewgroup);

//Get one reference to your Typeface (placed in your assets folder)
Typeface font = Typeface.createFromAsset(getAssets(), "My-Font.ttf");

//Call setTypeface with this root and font
setTypeface(root, font);

public void setTypeface(ViewGroup root, Typeface font) {
    View v;

    //Cycle through all children
    for(int i = 0; i < root.getChildCount(); i++) {
        v = root.getChildAt(i);

        //If it's a TextView (or subclass, such as Button) set the font
        if(v instanceof TextView) {
            ((TextView)v).setTypeface(font);

        //If it's another ViewGroup, make a recursive call
        } else if(v instanceof ViewGroup) {
            setTypeface(v, font);
        }
    }
}

This way you keep only one reference to your Typeface, and you don't have to hard code any of your View IDs.

You can also just build this into a custom subclass of Activity, and then have all of your Activites extend your custom Activity instead of just extending Activity, then you only have to write this code once.

Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • This wouldn't consume a lot of memory? – Yauraw Gadav Sep 17 '12 at 15:11
  • Nope. Out of curiosity, why do you think it would? – Kevin Coppock Sep 17 '12 at 15:13
  • You are setting typeface everytime you get a TextView, so for each textView it wouldn't allocate memory separately? beside this am using a ListView with tons of items. – Yauraw Gadav Sep 17 '12 at 15:17
  • 2
    Yeah, I do this in my ListViews with hundreds of items with no problem. As long as it's a class variable and you're not creating a new Typeface reference for every item, it's going to be using the same Typeface reference for every TextView. – Kevin Coppock Sep 17 '12 at 15:20
  • What if Im inflating layouts in my application, How can I do it then? – Yauraw Gadav Sep 17 '12 at 16:43
  • 1
    Just call setTypeface on that layout you inflate instead of the one you find with `findViewById()`. You can pass in *any* ViewGroup to that method and it will work, whether you find it by ID or inflate in in code. – Kevin Coppock Sep 17 '12 at 16:49