【问题标题】:Custom Fonts in Android: java.lang.RuntimeExceptionAndroid 中的自定义字体:java.lang.RuntimeException
【发布时间】:2016-03-01 03:32:46
【问题描述】:
我正在尝试在 Android Studio 应用程序的 TextView 中使用自定义字体,但出现以下错误:
这是一个空指针异常;在下面的代码中,txt 是 null 出于某种原因:
Java:
TextView txt;
txt.setText("A");
txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);
XML:
android:id="@+id/custom_font"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="A"
谢谢!
【问题讨论】:
标签:
java
android
xml
android-studio
【解决方案1】:
有了你的这一部分,
TextView txt;
txt.setText("A");
暗示您在空对象中调用方法 setText()。要使用此方法,您必须先初始化 TextView。
所以改变这个
TextView txt;
txt.setText("A");
txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);
到
TextView txt;
txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);
txt.setText("A");
【解决方案2】:
这行:Caused by: java.lang.NullPointerException: Attempt to invoke the method 'void android.widget.TextView.setText(java.lang.CharSequence)... 让我假设问题是你在转换 txt = (TextView) findViewById(R.id.custom_font); 之前调用 txt.setText("A");。
相反,您应该这样做:
TextView txt = (TextView) findViewById(R.id.custom_font);
txt.setText("A");
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);
【解决方案3】:
你在初始化之前使用的是txt,所以这个会导致空指针异常。
在访问任何变量或对象之前,您必须正确初始化它。
喜欢
txt = (TextView) findViewById(R.id.custom_font);
txt.setText 什么的
【解决方案4】:
尝试更改您的代码,如下所示:
...
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Grundschrift.ttf");
...
View 的getContext() 方法获取当前上下文。