如何将arrayList <model>项添加到listView

时间:2017-03-20 11:02:49

标签: java android arraylist android-arrayadapter

我想将arrayList的每个元素添加到listView,这里我将一个arrayList传递给包含包名和大小的适配器, 如何迭代并显示listView中的所有项目。

 public class CCacheAdapter extends ArrayAdapter<CCacheInfo>
{
 private ArrayList<CCacheInfo> arrayList;
 private Context mContext;
 public CCacheAdapter(Context context, ArrayList<CCacheInfo> cacheInfos)
{
    super(context,0, cacheInfos);
    mContext=context;
    arrayList=cacheInfos;
}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    CCacheInfo cCacheInfo = getItem(position);
    ViewHolder oViewHolder;
    if (convertView == null)
    {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.cache_items, parent, false);
        oViewHolder =new ViewHolder();
        oViewHolder.mPackageName = (TextView)convertView.findViewById(R.id.package_name);
        oViewHolder.mPackageSize = (TextView)convertView.findViewById(R.id.package_size);
        oViewHolder.mPackageIcon = (ImageView)convertView.findViewById(R.id.appIcon);
        oViewHolder.mCheckbox = (CheckBox)convertView.findViewById(R.id.checkbox);
        convertView.setTag(oViewHolder);
    }else
    {
        oViewHolder = (ViewHolder)convertView.getTag();
    }
        oViewHolder.mPackageName.setText(cCacheInfo.m_szAppName);
        oViewHolder.mPackageSize.setText(CCleanTool.formatShortFileSize(mContext, cCacheInfo.m_nSize));
    return convertView;
}
private class ViewHolder
{
    TextView mPackageName;
    TextView mPackageSize;
    CheckBox mCheckbox;
    ImageView mPackageIcon;
 }
  }

1 个答案:

答案 0 :(得分:0)

只需将适配器设置为ListView,如下所示

ArrayList<CCacheInfo> cacheInfos = ... // you get your data from somewhere
ListView listView = (ListView) findViewById(R.id.list_view);
CCacheAdapter adapter = new CCacheAdapter(this, cacheInfos);
listView.setAdapter(adapter);