简体   繁体   English

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

[英]Custom Fonts in Android: java.lang.RuntimeException

I am trying to use a custom font within a TextView of an Android Studio application, but am getting the following error: 我正在尝试在Android Studio应用程序的TextView中使用自定义字体,但出现以下错误:

在此处输入图片说明

It's a null pointer exception; 这是一个空指针异常; in the below code, txt is null for some reason: 在以下代码中,出于某些原因, txtnull

Java : 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 : XML

android:id="@+id/custom_font"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="A"

Thanks! 谢谢!

With this part of your, 有了这部分,

TextView txt;
txt.setText("A");

implies that you are calling a method setText() in a null object. 表示您正在空对象中调用setText()方法。 To use this method, you have to first initialize the TextView. 若要使用此方法,您必须首先初始化TextView。

so change this 所以改变这个

TextView txt;
txt.setText("A");

txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);

to

TextView txt; 
txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);
txt.setText("A");

The line: Caused by: java.lang.NullPointerException: Attempt to invoke the method 'void android.widget.TextView.setText(java.lang.CharSequence)... makes me assume that the ploblem is you call txt.setText("A"); 该行: Caused by: java.lang.NullPointerException: Attempt to invoke the method 'void android.widget.TextView.setText(java.lang.CharSequence)...让我假设问题是您调用txt.setText("A"); before casting txt = (TextView) findViewById(R.id.custom_font); 在投射txt = (TextView) findViewById(R.id.custom_font); .

Instead you should do like this: 相反,您应该这样做:

TextView txt = (TextView) findViewById(R.id.custom_font);
txt.setText("A");
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);

Try to change your code like the below code: 尝试像下面的代码一样更改代码:

...
Typeface font = Typeface.createFromAsset(getContext().getAssets(),  "fonts/Grundschrift.ttf");
...

View's getContext() method to get the current context. View的getContext()方法可获取当前上下文。

You are using txt before initializing, so this one causes a null pointer exception. 您在初始化之前使用txt,因此这会导致空指针异常。

Before accessing any variable or object you have to initialize it properly. 在访问任何变量或对象之前,您必须正确地对其进行初始化。

like txt = (TextView) findViewById(R.id.custom_font); 像txt =(TextView)findViewById(R.id.custom_font);

txt.setText or something txt.setText之类的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM