自定义 ArrayAdapter

默认情况下 ,ArrayAdapter 类通过在每个项目上调用 toString() 并将内容放在 TextView 中来为每个数组项创建一个视图。

要为每个项创建复杂视图(例如,如果你希望每个数组项都有 ImageView),请扩展 ArrayAdapter 类并覆盖 getView() 方法以返回每个项目所需的 View 类型。

例如:

public class MyAdapter extends ArrayAdapter<YourClassData>{

    private LayoutInflater inflater;

    public MyAdapter (Context context, List<YourClassData> data){
        super(context, 0, data);
        inflater = LayoutInflater.from(context);
    }

    @Override
    public long getItemId(int position)
    {
        //It is just an example
        YourClassData data = (YourClassData) getItem(position);
        return data.ID;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent)
    {
        ViewHolder viewHolder;
        if (view == null) {
            view = inflater.inflate(R.layout.custom_row_layout_design, null);
            // Do some initialization
        
            //Retrieve the view on the item layout and set the value.
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
         }
         else {
             viewHolder = (ViewHolder) view.getTag();
         }
         
        //Retrieve your object    
        YourClassData data = (YourClassData) getItem(position);
       
        viewHolder.txt.setTypeface(m_Font);    
        viewHolder.txt.setText(data.text);              
        viewHolder.img.setImageBitmap(BitmapFactory.decodeFile(data.imageAddr));
        
        return view;
    
    }

    private class ViewHolder
    {
         private final TextView txt;
         private final ImageView img;

         private ViewHolder(View view) 
         {
             txt = (TextView) view.findViewById(R.id.txt);
             img = (ImageView) view.findViewById(R.id.img);
         }
    }
}