java - Android 中的自定义字体 : java. lang.RuntimeException

标签 java android xml android-studio

我尝试在 Android Studio 应用程序的 TextView 中使用自定义字体,但出现以下错误:

enter image description here

这是一个空指针异常;在下面的代码中,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"

谢谢!

最佳答案

有了你的这一部分,

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

关于java - Android 中的自定义字体 : java. lang.RuntimeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35714172/

相关文章:

java - JGame可以双屏全屏吗?

java - 如何使用 Retrofit2 处理包装在一个 JSON 对象中的 JSON 对象?

android - Facebook Likeview 不工作

java.util.NoSuchElementException 在 java 中使用迭代器

Java generics unchecked cast - 可以在运行时检查吗?

android - 单机返回表达式解释

sql - 在 PostgreSQL 的 TEXT 列上使用 XMLEXISTS

c# - 如何使用 XDocument.Save 使用属性的自定义缩进保存文件

xml - MarkLogic 5 返回包含在 CDATA 中的元素

java - 如何在android应用程序中截取状态栏内容的屏幕截图?