【问题标题】:Calling Typeface.createFromAsset from custom component causes npe in AndroidStudio从自定义组件调用 Typeface.createFromAsset 会导致 Android Studio 中出现 npe
【发布时间】:2016-12-18 21:00:47
【问题描述】:

由于在xml中指定自定义字体是impossible,所以我想继承所有组件并在那里添加新参数fontType。例如,如果我想要一个带有自定义字体的按钮,它看起来像这样:

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

嗯,这个东西在模拟器/真正的 Android 设备中完美运行。但是 android studio (2.1.2.0-1) 的预览会抛出 NPE。我可以继续忍受痛苦并测试设备中的所有内容,但如果没有 AndroidStudio 预览版,这会使开发变得非常缓慢。

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)

这是 AndroidStudio 的错误,还是我应该在其他地方调用 createFromAsset?就像在topic 中告诉的人一样

有什么想法吗?

最好的问候,

【问题讨论】:

    标签: android-studio android-custom-view android-fonts android-custom-attributes


    【解决方案1】:

    啊,nvm 它是bug 中的AndroidStudio。修复于Android Studio 2.2 Preview 7

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 2021-05-24
      • 1970-01-01
      • 2016-09-04
      相关资源
      最近更新 更多