我正在开发一个Android应用程序,它需要将TextView的默认字体系列(字体)设置为Roboto,我扩展了TextView并将字体定义为Roboto-Light.tff,但应用程序崩溃时出现NullPointerException。这是班级:
public class RobotoTextView extends TextView {
public RobotoTextView(Context context, AttributeSet attrs) {
super(context);
// Eclipse edit mode doesn't show the font
if (isInEditMode()) {
return;
}
if(attrs != null) {
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView);
String fontName = styledAttrs.getString(R.styleable.RobotoTextView_typeface);
styledAttrs.recycle();
if (fontName != null) {
Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
setTypeface(typeface);
}
}
}
}
这是我的XML attrs.xml:
<resources>
<declare-styleable name="RobotoTextView">
<attr name="typeface" format="string" />
</declare-styleable></resources>
这里是第54行引发异常的代码,知道提供的参数不为null。
这是错误:
这是drawer_list_item.xml:
<ImageView
android:id="@+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="@string/desc_list_item_icon"
android:src="@drawable/ic_launcher"
android:layout_centerVertical="true" />
<com.mhproductions.widget.RobotoTextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="@id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="@color/list_item_title"
android:gravity="center_vertical"
android:paddingRight="40dp"
app:typeface="Roboto-Light"/>
<com.mhproductions.widget.RobotoTextView
android:id="@+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/counter_bg"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:textColor="@color/counter_text_color"
app:typeface="Roboto-Light"/>
答案 0 :(得分:0)
看起来像getTitle()返回null。我永远不会理解那些他们不理解的错误的人,并且事先断言,关于代码的一切都是正确的。
我认为它必须是getTitle(),因为54以上的行中的getIcon()完成。
答案 1 :(得分:0)
1)确保R.layout.drawer_list_item有一个ID为R.id.title的TextView
2)在RobotoTextView中实现所有三个构造函数
3)确保实例化navDrawerItems并且它们不包含空项。