NullPointerException with custom font from assets

∥☆過路亽.° 提交于 2019-12-08 09:51:00

问题


I'm trying to use custom font in my application, but i got that exception when when run the app:

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

I have a working font and it's in the right path and that's my code:

private TextView tv;
private Typeface tf;

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

That's my 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>


回答1:


tv is null. For whatever reason (e.g., failure to call setContentView()), you do not have a widget in the activity that can be found via R.id.wlcText.



来源:https://stackoverflow.com/questions/30549351/nullpointerexception-with-custom-font-from-assets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!