【发布时间】:2014-10-19 13:36:01
【问题描述】:
我已经尝试了所有我能找到的方法来让自定义字体正常工作,但我不断收到“空指针异常”。这是我所做的:
在“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();
}
代码的第一部分列出了“字体”文件夹中的所有项目,我得到一个显示“r.ttf”的弹出窗口。
代码的第二部分尝试加载字体,我从那里得到一个带有“空指针异常”的弹出窗口。
任何想法我做错了什么?谢谢!
编辑: 异常由此引发: txt.setTypeface(font) 上的 java.lang.NullPointerException;
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,并且在你尝试访问它时它已经被夸大了吗?
-
我有那个ID,我可以按住ctrl+click_on_id,它会把我带到xml文件。不确定“在您尝试访问它时已经膨胀”是什么意思,我在“onCreate”事件中有此代码
-
你有 setContentView 在正确的 xml 上吗?
-
我有 setContentView(R.layout.activity_main);谢谢!我用布局代码更新了我的问题。