我尝试在 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"
谢谢!
最佳答案
有了你的这一部分,
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/