我想用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;
我想在列表中显示
现在的问题是:如何解决这个问题?
fromColumns
的内容与text
值匹配elements
列表绑定到列表中以便显示答案 0 :(得分:1)
创建自定义适配器。您可以延长BaseAdapter
或ArrayAdapter
。 ArrayAdapter
是一个通用类,因此它适用于此示例。
可能的实施:
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;
}
}