我已经尝试了所有我能找到的方法来使自定义字体正常工作,但我不断收到“空指针异常”。这是我所做的:
在“assets”目录中创建了“fonts”文件夹。
从此处下载 Google 的“Roboto”字体:http://www.fontspace.com/google-android/roboto
将文件“Roboto-Regular.ttf”重命名为“r.ttf”
上传到assets/fonts/目录
是否进行了项目->清理
现在我有这个代码:
try {
fileList = am.list("fonts");
if (fileList != null)
{
for ( int i = 0;i<fileList.length;i++)
{
Toast.makeText(getApplicationContext(), fileList[i] + "!", Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try {
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/r.ttf");
TextView txt = (TextView) findViewById(R.id.rowTextView);
txt.setTypeface(font);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
代码的第一部分列出了“fonts”文件夹中的所有项目,我得到一个显示“r.ttf”的弹出窗口。
代码的第二部分尝试加载字体,我从那里得到一个带有“空指针异常”的弹出窗口。
有什么想法我做错了什么吗?谢谢!
编辑: 异常是这样抛出的: txt.setTypeface(font) 上的 java.lang.NullPointerException;
编辑2:
这是我的activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kb.klog.MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
这是我尝试将字体更改为的行:/res/layout/row.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="#aaa"
android:textSize="18sp">
最佳答案
txt的值为空,因为当时该行还没有膨胀。
我建议使用这个答案https://stackoverflow.com/a/9035924/2160877
一般来说,您应该创建自己的扩展 TextView 的类。然后在 xml 中引用该类即可。
如果链接被删除,这里是您的类的代码(取自链接,并根据您的情况进行了一些修改):
package com.yourPackageNameGoesHere;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"r.ttf");
setTypeface(tf);
}
}
然后你的/res/layout/row.xml 将如下所示:
<com.yourPackageNameGoesHere.MyTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="#aaa"
android:textSize="18sp">
关于android - 自定义字体空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451055/