Skip to content

Instantly share code, notes, and snippets.

@pookie13
Created February 16, 2016 13:27
Show Gist options
  • Save pookie13/b627a59f5ee4e38efd05 to your computer and use it in GitHub Desktop.
Save pookie13/b627a59f5ee4e38efd05 to your computer and use it in GitHub Desktop.
public class FontChangeCrawler
{
private Typeface typeface;
public FontChangeCrawler(Typeface typeface)
{
this.typeface = typeface;
}
public FontChangeCrawler(AssetManager assets, String assetsFontFileName)
{
typeface = Typeface.createFromAsset(assets, assetsFontFileName);
}
public void replaceFonts(ViewGroup viewTree)
{
View child;
for(int i = 0; i < viewTree.getChildCount(); ++i)
{
child = viewTree.getChildAt(i);
if(child instanceof ViewGroup)
{
// recursive call
replaceFonts((ViewGroup)child);
}
else if(child instanceof TextView)
{
// base case
((TextView) child).setTypeface(typeface);
}
}
}
}
Replacing Activity fonts goes a long way, but most of us also have a plethora of ListViews. The list items in a ListView are built within an adapter, not within an Activity. Therefore, you will also need to use the FontChangeCrawler in your adapters:
if(convertView == null)
{
convertView = inflater.inflate(R.layout.listitem, null);
fontChanger.replaceFonts((ViewGroup)convertView);
}
...
What's Not Handled?
I will leave handling the ActionBar as an exercise for the reader. Also, consider how you might handle widgets whose typeface you don't want to change.
@Override
public void setContentView(View view)
{
super.setContentView(view);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "font.otf");
fontChanger.replaceFonts((ViewGroup)this.findViewById(android.R.id.content));
}
If you are not familiar with android.R.id.content, it is the official ID given to the root View within an Activity's layout.
Consider placing the above logic in a BaseActivity class
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "font.otf");
fontChanger.replaceFonts((ViewGroup) this.getView());
}
You will need to apply the FontChangeCrawler to each Fragment as well. Consider placing this logic in a BaseFragment class.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment