NullPointerException,带有来自资产的自定义字体

Moh*_*med 0 android nullpointerexception android-assets

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

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

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

private TextView tv;
private Typeface tf;

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

这是我的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>
Run Code Online (Sandbox Code Playgroud)

Com*_*are 6

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

  • 他可能不会调用`setContentView()`或在`findViewById()`之后调用它 (2认同)