0

Comme il s'agit de impossible pour spécifier une police personnalisée au format XML, je souhaite hériter de tous les composants et y ajouter un nouveau paramètre fontType. Par exemple, si je veux un bouton avec la police personnalisée, il ressemblerait à ceci:L'appel de Typeface.createFromAsset à partir du composant personnalisé provoque npe dans AndroidStudio

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);; 
    } 
} 

Eh bien, cette chose fonctionne parfaitement dans l'émulateur/réel appareil Android. Mais l'aperçu pour android studio (2.1.2.0-1) lance NPE. Je peux continuer à souffrir et à tester tout ce qui se passe dans les appareils, mais cela rendrait le développement très lent sans l'aperçu d'AndroidStudio.

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) 

Est-ce bogue Android Studio, ou devrais-je appeler createFromAsset ailleurs? Comme gars dit dans ce topic

Des pensées?

Meilleures salutations,

Répondre

0

Ah, NVM c'est un bug dans AndroidStudio. Fixé en Android Studio 2.2 Preview 7