由于在xml中指定自定义字体是不可能,所以我希望继承所有组件并在其中添加新的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的预览版(2.1.2.0-1)会抛出NPE。我可以在设备中不断地忍受和测试所有的东西,但是这会使开发速度降低w/o 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
?就像盖伊在主题上说的
有什么想法吗?
诚挚的问候,
发布于 2016-12-18 13:00:47
啊,nvm --这是错误 in AndroidStudio
。固定在Android Studio 2.2 Preview 7
中
https://stackoverflow.com/questions/41208519
复制相似问题