Android使用自定义字体作为列表视图项

时间:2011-10-30 09:55:51

标签: android textview typeface

您好我需要帮助为listview项目使用自定义字体。我从资产文件夹中得到了这样的字体:

Typeface font = Typeface.createFromAsset(getAssets(), "hermesbgbold.otf"); 

我正在尝试为我的listview项目设置它,但问题是我正在使用SimpleAdapter作为我的ListView而TextView是在另一个XML中,我将其用作我的列表视图的contentView 。以下是更好理解的代码:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.events);
// code

SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.events_items,
                new String[]{ICON,TITLE, INFO}, new int[]{ R.id.thumb,R.id.title, R.id.dates})

}

因此,我想在自定义字体中使用的textview位于events_items.xml。那么如何设置titledates来使用此自定义字体?

1 个答案:

答案 0 :(得分:1)

创建自己的自定义适配器并为文本设置字体。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // ViewHolder will buffer the assess to the individual fields of the row
    // layout

    ViewHolder holder;
    // Recycle existing view if passed as parameter
    // This will save memory and time on Android
    // This only works if the base layout for all classes are the same
    View rowView = convertView;
    if (rowView == null) {

        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.main_listview, null, true);

        holder = new ViewHolder();
        holder.textView = (TextView) rowView.findViewById(R.id.main_name);
        rowView.setTag(holder);

    } else {
        holder = (ViewHolder) rowView.getTag();
    }

    Typeface font = Typeface.createFromAsset(getAssets(), "hermesbgbold.otf"); 
    holder.textView.setTypeface(font);
    holder.textView.setText(title);

    return rowView;
}