Skip to content

Instantly share code, notes, and snippets.

@sergii-frost
Last active December 31, 2015 15:09
Show Gist options
  • Save sergii-frost/8004882 to your computer and use it in GitHub Desktop.
Save sergii-frost/8004882 to your computer and use it in GitHub Desktop.
Gist to set custom font to all textviews and buttons in viewgroup
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FontUtils {
public static Typeface getOpenSansLight(AssetManager am) {
return Typeface.createFromAsset(am, "fonts/OpenSans-Light.ttf");
}
// recursively apply typeface to our textviews
public static final void setTypeface(ViewGroup viewGroup, Typeface typeface) {
if (viewGroup == null) return;
int children = viewGroup.getChildCount();
for (int i=0; i<children; i++) {
View view = viewGroup.getChildAt(i);
if (view instanceof ViewGroup) setTypeface((ViewGroup)view, typeface);
if (view instanceof TextView) {
((TextView)view).setTypeface(typeface);
} else if (view instanceof Button) {
((Button)view).setTypeface(typeface);
}
}
}
}
@sergii-frost
Copy link
Author

Further usage in Fragments:

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(getView() instanceof ViewGroup) {
            FontUtils.setTypeface((ViewGroup) getView(), FontUtils.getOpenSansLight(getActivity().getAssets()));
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment