我想要在我的ArrayAdapter
中改变TextView
的字体。字体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);
用于listitem布局的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
,但这并不能达到我想要的效果。如何将
Adapter
中的 TextView
字体更改为自定义字体?更新
根据 Pixie 的建议,我创建了一个扩展了
ArrayAdapter<MenuItem>
的 MenuItemAdapter
: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);
但是现在我的应用程序在
ListActivity
的onCreate
之后崩溃,但在达到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;
}
这很有效。:)