Calling Typeface.createFromAsset from custom component causes npe in AndroidStudio

298 views Asked by At

Since it's impossible to specify custom font in xml, I want to inherit all components and add new param fontType there. For example if I want a button with custom font it would look like this:

activity.xml:

<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto">
    <package.Button app:fontType="GothamPro" />
</LinearLayout>

attr.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="fontType" format="enum">
        <enum name="GothamProMedium" value="0"/>
        <enum name="GothamPro" value="1"/>
    </attr>
    <declare-styleable name="Button">
        <attr name="fontType"/>
    </declare-styleable>

</resources>

Button.java:

public class Button extends android.widget.Button {

   public static SparseArray<String> sp = new SparseArray<>();

   static {
      sp.put(0, "fonts/gotham/GothamProMedium.ttf");
      sp.put(1, "fonts/gotham/GothamProRegular.ttf");
   }

    private String path;

    public Button(Context context) {
        super(context);
    }
    public Button(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public Button(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Button);
            path = sp.get(a.getInt(R.styleable.Button_fontType, -1));
            a.recycle();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), path);
        setTypeface(tf);;
    }
}

Well this thing works perfectly in Emulator/real Android Device. But preview for android studio (2.1.2.0-1) throws NPE. I can keep suffering and test everything in devices but it would make development really slow w/o AndroidStudio preview.

enter image description here

java.lang.NullPointerException
at android.graphics.Typeface.createAssetUid(Typeface.java:219)
at android.graphics.Typeface.createFromAsset(Typeface.java:193)
at com.mypackage.Button.onAttachedToWindow(Button.java:46)
at android.view.View.dispatchAttachedToWindow(View.java:15509)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2923)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2923)

Is this AndroidStudio bug, or I should call createFromAsset somewhere else? Like guy told in this topic

Any thoughts?

Best regards,

1

There are 1 answers

0
deathangel908 On BEST ANSWER

Ah, nvm it's a bug in AndroidStudio. Fixed in Android Studio 2.2 Preview 7