【问题标题】:NullPointerException with custom font from assets来自资产的自定义字体的 NullPointerException
【发布时间】:2015-05-30 17:41:51
【问题描述】:

我正在尝试在我的应用程序中使用自定义字体,但在运行应用程序时出现异常:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference

我有一个工作字体,它在正确的路径中,这就是我的代码:

private TextView tv;
private Typeface tf;

    tv = (TextView) findViewById(R.id.wlcText);
    tf = Typeface.createFromAsset(getAssets(), "en_font.ttf");
    tv.setTypeface(tf);

这是我的 XML:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/mainView"
    android:background="@color/semi_transparent_black"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/wlcText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:text="Test"
        android:textSize="25sp" />

</LinearLayout>

【问题讨论】:

  • 你能发布onCreate()代码吗?

标签: android nullpointerexception android-assets


【解决方案1】:

tvnull。无论出于何种原因(例如,未能调用setContentView()),您的活动中都没有可以通过R.id.wlcText 找到的小部件。

【讨论】:

  • 我编辑了问题并显示了xml,请问有什么问题?
  • @commons tf 为 null 而不是 tv
  • @Codester tvnull。他试图在一个空对象上调用 setTypeface 方法。
  • @issathink 通过查看他的 xml,他的 tv 怎么可能是空的?
  • 他可能没有调用setContentView()或者在findViewById()之后调用它
猜你喜欢
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
相关资源
最近更新 更多