自定義 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);
         }
    }
}