android - ArrayAdapter 中 textview 的自定义字体

标签 android

我正在尝试更改 TextView 的字体在我的 ArrayAdapter .字体chantelli_antiqua.ttf在 Assets 文件夹中。

<罢工> 这是我的 Java 代码:

listItemAdapter = new ArrayAdapter<MenuItem>(this, R.layout.listitem, menuItems);

Typeface font = Typeface.createFromAsset(getAssets(), "chantelli_antiqua.ttf");  
TextView v = (TextView)listItemAdapter.getView(0, null, null);
v.setTypeface(font);

用于列表项布局的 xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="30sp"
/>

我很确定问题出在 Adapter.getView(int, View, ViewGroup) 上方法。我只是不太明白要传递什么作为变量并尝试了 null .但这并没有达到我想要的效果。

如何更改 TextView 的字体在Adapter到自定义字体?

更新

根据 Pixie 的建议,我创建了一个 MenuItemAdapter延伸 ArrayAdapter<MenuItem> :

public class MenuItemAdapter extends ArrayAdapter<MenuItem>
{
    private Typeface font;

    public MenuItemAdapter(Context context, int textViewResourceId, List<MenuItem> objects) 
    {
        super(context, textViewResourceId, objects);

        font = Typeface.createFromAsset(context.getAssets(), "chantelli_antiqua.ttf"); 
    }

    @Override  
    public View getView(int position, View view, ViewGroup viewGroup)
    {
        ((TextView)view).setTypeface(font);
        return super.getView(position, view, viewGroup);
    }
}

并将我的 java 代码更改为:

listItemAdapter = new MenuItemAdapter(this, R.layout.listitem, menuItems);

但现在我的应用程序在 onCreate 之后崩溃了的 ListActivity , 但在遇到 getView(...) 中的断点之前,我还没有弄清楚为什么。有什么建议吗?

更新2

将 getView(...) 的代码更改为:

@Override  
public View getView(int position, View view, ViewGroup viewGroup)
{
 View v = super.getView(position, view, viewGroup);
 ((TextView)v).setTypeface(font);
 return v;
}

这行得通。 :)

最佳答案

您不应调用适配器的 getView() 方法。 ListView 为您做这件事。您必须扩展 ArrayAdapter 类并改写 getView() 方法。在此方法中,您必须扩充新 View 或重新使用 convertView 并为此 View 设置字体。

关于android - ArrayAdapter 中 textview 的自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5911198/

相关文章:

android - 如何模拟Android Market App?

android - 我们可以在 apk 文件中 bundle 一个目录吗?

android - 如何以编程方式在 couchbase android 中添加 ssl 证书

安卓 ndk(cmake) : 'undefined reference to ` __android_log_write' when using log api in the second jni library

android - 在抽象类中获取应用上下文

android - 查看扬声器是否正在使用?

android - 滑动选择安卓

android - 如何编写自定义View的set方法

android - 如何使 PagerSnapHelper 在 RecyclerView 中双向捕捉?

android - 如何在onPostExecute Asynctask中设置List Adapter?