我可以用我自己的班级列表填写列表视图吗?

时间:2013-05-28 09:57:56

标签: android

我想用ListView我自己的元素填充LinkedList<String>

我的班级看起来像这样:

public class Foo {
    public String text;
}

这是我的适配器和列表:

String[] fromColumns = {"X"};
int[] toViews = {android.R.id.text1};
mAdapter = new SimpleCursorAdapter(this, 
        android.R.layout.simple_list_item_1, null,
        fromColumns, toViews, 0);
list = (ListView)findViewById(R.id.list);
list.setAdapter(mAdapter);

我还有一个LinkedList<Foo> elements;我想在列表中显示

现在的问题是:如何解决这个问题?

  1. 我不知道写入fromColumns的内容与text值匹配
  2. 我不知道如何将我的elements列表绑定到列表中以便显示

2 个答案:

答案 0 :(得分:1)

创建自定义适配器。您可以延长BaseAdapterArrayAdapterArrayAdapter是一个通用类,因此它适用于此示例。

可能的实施:

public class CustomAdapter extends ArrayAdapter<Item> {

    public CustomAdapter(Context context, List<Item> items) {
        super(context, 0, items);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(getContext(), R.layout.some_layout, null);
            holder = new ViewHolder();
            holder.textView = (TextView) convertView.findViewById(R.id.textView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(getItem(position).getText());
        return convertView;
    }

    private class ViewHolder {
        TextView textView;
    }
}

现在像这样设置适配器:

CustomAdapter customAdapter = new CustomAdapter(context, getList());
listView.setAdapter(customAdapter);

答案 1 :(得分:0)

您需要为此创建自定义适配器..

像:

public class AdapterCategoryList extends BaseAdapter {
    private Context context;
    private ArrayList<SetterCategoryNames> categoryNames;
    public AdapterCategoryList( Context context, ArrayList<SetterCategoryNames> categoryNames ){
        this.context    =   context;
        this.categoryNames = categoryNames;
    }

    @Override
    public int getCount() {       
        return categoryNames.size();
    }

    @Override
    public Object getItem(int position) {       
        return categoryNames.get(position);
    }

    @Override
    public long getItemId(int position) {        
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        if ( convertView == null ) {
            convertView = View.inflate(context, R.layout.listitem_category_list, null);
            holder = new Holder();
            holder.mTxtCategoryImage = (TextView) convertView.findViewById(R.id.txtCategoryListItem);
            convertView.setTag(holder);
        }else{
            holder = (Holder) convertView.getTag();
        }        
        holder.mTxtCategoryImage.setBackgroundResource( categoryNames.get(position).getCategoryImage() );        
        return convertView;
    }

    class Holder {
        TextView mTxtCategoryImage;
    }

}