Android listview的自定义字体

时间:2013-03-08 11:55:37

标签: android listview fonts

我的Android活动有自定义字体。

MainActivity.class

    private void initControls() {
    // TODO Auto-generated method stub
    header = (TextView) findViewById (R.id.tvAccommodations);
    lv = (ListView) findViewById (R.id.lvAccommodations);
    text = (TextView) findViewById (R.id.textView);

    Typeface tf = Typeface.createFromAsset(getAssets(),
            "fonts/heartbre.ttf");
    header.setTypeface(tf);
    text.setTypeface(tf);



    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                    R.array.abra_hotel, R.layout.custom_list_text);
            lv.setAdapter(adapter);
            header.setText(value);

custom_list_text.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:text="@string/app_name"
android:paddingLeft="6dip" />

Android抛出NullPointerException。为什么会这样?任何帮助表示赞赏。感谢。

logcat的:

    03-08 19:48:03.859: E/AndroidRuntime(413): Caused by: java.lang.NullPointerException
    03-08 19:48:03.859: E/AndroidRuntime(413):  at com.say.philippineexplorer.PlaceAccommodations.initControls(PlaceAccommodations.java:34)
    03-08 19:48:03.859: E/AndroidRuntime(413):  at com.say.philippineexplorer.PlaceAccommodations.onCreate(PlaceAccommodations.java:22)

2 个答案:

答案 0 :(得分:10)

这是自定义适配器类和构造函数

class CustomAdapter extends ArrayAdapter<CharSequence>{

    Context context; 
    int layoutResourceId;    
    CharSequence data[] = null;
    Typeface tf; 

public CustomAdapter(Context context, int layoutResourceId, CharSequence[] data, String FONT ) { 
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
    tf = Typeface.createFromAsset(context.getAssets(), FONT);
}   

将您要使用的字体放在您的资源文件夹中,并填写您的列表视图:

listAdapter = new CustomAdapter(this, R.layout.custom_list_text, R.array.abra_hotel, "name_of_font.ttf");

答案 1 :(得分:2)

你不能直接将字体应用于listview,你需要为listview创建自定义适配器并更改字体以获取更多详细信息点击下面的堆栈帖子已经讨论过。

How to change color and font on ListView