安卓列表视图自定义字体

4

我在我的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)

发布日志异常 - Srikanth
@bEtTyBarnes,第34行和第22行是什么? - DjHacktorReborn
这行代码:text.setTypeface(tf); - user1410081
@bEtTyBarnes:请发布您完整的 Activity onCreate 方法代码。 - ρяσѕρєя K
@bEtTyBarnes:您需要重写getView方法来设置自定义字体,请参考此示例并更改您的代码:http://pastebin.com/bcVSmPJG - ρяσѕρєя K
2个回答

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");

它对我的适配器不起作用,这是SO:http://stackoverflow.com/questions/21439707/typeface-not-taking-place-in-custom-arrayadapter?answertab=active#tab-top - vlio20
1
你创建了一个名为 tf 的属性,并将 Typeface 赋值给它,但是 tf 没有被分配到任何东西。这段代码如何设置项渲染器的字体? - William Grand
我将字体文件放在 "src/assets/fonts/myfont.ttf",并将其传递到适配器中的 "fonts/myfont.ttf",它可以正常工作。谢谢! - Anna Billstrom

2

你不能直接将字体应用于ListView,并且需要为ListView创建自定义适配器并更改其字体。有关更多详细信息,请点击下面的Stack文章进行讨论。

如何在ListView上更改颜色和字体


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接