【问题标题】:Custom font for Android listviewAndroid列表视图的自定义字体
【发布时间】:2013-02-23 23:08:57
【问题描述】:

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

【问题讨论】:

  • 发布日志异常
  • @DjHacktorReborn 我更新了我的帖子
  • @bEtTyBarnes 第 34 行和第 22 行是什么?
  • 这一行:text.setTypeface(tf);
  • @bEtTyBarnes :发布您的完整 Activity onCreate 方法代码

标签: android listview fonts


【解决方案1】:

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

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:stackoverflow.com/questions/21439707/…
  • 您创建了一个名为tf 的属性并为其设置了Typeface,但tf 未分配给任何内容。这段代码如何设置item renderer的字体?
  • 我把字体 sin "src/assets/fonts/myfont.ttf" 并传递给适配器 "fonts/myfont.ttf" 并且它工作。谢谢!
【解决方案2】:

您不能将字体直接应用于列表视图,您需要为列表视图创建自定义适配器并更改其字体以获取更多详细信息,请单击下面的堆栈帖子,它已经讨论过。

How to change color and font on ListView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多