Saturday, May 12, 2012

Automatic assignment of custom font in android activity

Custom font in Android is unfortunately not a theme question (correct me if I'm wrong) but is in fact quite simple to implement. In your common base activity overload the setContentView like this:
	public void setContentView(int layoutResId) {
		View root = getWindow().getDecorView().getRootView();
		if (root instanceof ViewGroup) {
			Typeface font = Typeface.createFromAsset(getAssets(), "<<YOUR FONT FROM ASSETS>>");
			iterateKids(root, font);

	private void iterateKids(View view, Typeface font) {
		if (view instanceof TextView) {
		} else if (view instanceof ViewGroup) {
			ViewGroup group = ((ViewGroup)view);
			for (int x=0; x<group.getChildCount(); x++) {
				iterateKids(group.getChildAt(x), font);

it spends aboout 0.3 ~ 2ms on every child in hierarchy (on emulator) so as long as you optimize your layouts to be less than 100 elements a screen it's definitely okay.