20.9.11

Android Recursively change fonts ?

I think it's time to start blogging about android :)

I just got my Samsung Galaxy S2 a week ago and it's been so fun playing with !

So today i'm gonna show how to use custom fonts, There is a nice artical about Styling TextViews in here: Customize Android Fonts

You can see there that they are accessing a TextView using it's ID and then changing the font of the spacific TextView.
TextView txt = (TextView) findViewById(R.id.custom_font);  
Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");  
txt.setTypeface(font);  
Now that can be a pain in the a** if you have alot of TextViews in your page...
So iv'e created a Recursive that changes all TextView's & Button's fonts on the same page :)
void UpdateFonts(ViewGroup parent, Typeface font) {
  for (int i = 0; i < parent.getChildCount(); i++) {
   View child = parent.getChildAt(i);
   if (child instanceof ViewGroup) {
    UpdateFonts((ViewGroup) child, font);
   } else if (child != null) {
    if (child.getClass() == TextView.class) {
     ((TextView) child).setTypeface(font);
    } else if (child.getClass() == Button.class) {
     ((Button) child).setTypeface(font);
    }
   }
  }
 }
This is an eay recursive that loops through all children of a parent element and changes all of his children's fonts.
You can call it like that if you want all page:
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/choco.ttf");
ViewGroup rootView = (ViewGroup) findViewById(android.R.id.content).getRootView();
UpdateFonts(rootView, font);
Hope you enjoyed my first Android article :)
See you next time ;)

No comments:

Post a Comment