我尝试了一切可以找到自定义字体的工作,但我不断收到'空指针异常。以下是我所做的:自定义字体空指针异常
在'资产'目录中创建文件夹'字体'。
下载谷歌的 '的Roboto' 从这里字体:http://www.fontspace.com/google-android/roboto
重命名的文件 '的Roboto-Regular.ttf' 到 'r.ttf'
上传到资产/ 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();
}
代码的第一部分列出'字体'文件夹中的所有项目,我得到一个弹出窗口显示'r.ttf'。
代码的第二部分尝试加载字体,我从那里用'空指针异常'得到一个弹出窗口。
任何想法我做错了什么?谢谢!
编辑: 该异常是在由该抛出: 显示java.lang.NullPointerException上txt.setTypeface(字体);
EDIT2:
这是我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">
您确定您有该ID,并且在您尝试访问它的位置时它已经膨胀了吗? – helleye 2014-10-19 13:52:13
我有这个ID,我可以按住ctrl + click_on_id,它将我带到xml文件。不确定你在'尝试访问它时已经膨胀了'的意思,我在'onCreate'事件中有这个代码 – user3578847 2014-10-19 13:55:37
你有** setContentView **正确的xml吗? – helleye 2014-10-19 13:58:53