AkasH AkasH - 1 year ago 151
Android Question

Set font through calligraphy to all buttons in an Application

I've seperated my UI part into a lib and am creating my styles there.

I have a default style for all buttons and I'm setting it like this.

<style name="MyTheme.Default">
<item name="buttonStyle">@style/button</item>

My button style is

<style name="button">
<item name="fontPath">fonts/myfont.ttf</item>
<item name="android:gravity">center</item>
<item name="android:clickable">true</item>
<item name="android:textSize">14sp</item>

I want this button style to be applied to all buttons without me calling the @style attribute. Everything seems to work fine except for the font. It's not getting applied.

If I call using the @style attribute, it seems to apply the font.

I can apply the font for all the texts in the application using textAppearance, this changes the font of my button as well. but this is behaviour I don't want.

So, how can I apply a custom to buttons through my lib without explicitly using the @style attribute on every button.

Answer Source

I think that I've found the problem. If you are using AppCompat the font wont be applied to some widgets like Button, because AppComat replace the components with AppCompat versions when inflating (e.g. Button--->AppCompatButton).

So you can't do do it using only xml. A possible way using Java would be:

private void changeFont(ViewGroup layout) {//Where 'layout' is the parent
    for (int i = 0; i < layout.getChildCount(); i++) {
        View child = layout.getChildAt(i);
        if (child instanceof ViewGroup) {
            changeFont((ViewGroup) child);
        } else if (child instanceof Button) {
            child.setTypeface(...//The font that you want

Another option, if your minSDK>16 is avoid using AppCompat. I haven't tried this but it shoul work

Hope this helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download