【问题标题】:Custom Fonts in Android: java.lang.RuntimeExceptionAndroid 中的自定义字体:java.lang.RuntimeException
【发布时间】:2016-03-01 03:32:46
【问题描述】:

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

这是一个空指针异常;在下面的代码中,txtnull 出于某种原因:

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() 方法获取当前上下文。

      【讨论】:

        猜你喜欢
        • 2011-04-12
        • 2015-12-29
        • 2015-06-08
        • 2014-08-18
        • 2015-08-13
        • 2011-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多