我有一个listview,我使用cusome ArrayAdapter填充,listview中的每一行都包含图像和 Headers .
我按照本教程http://www.vogella.com/tutorials/AndroidListView/article.html创建自定义arrayadapter并使用它填充我的listview,如下所示:
在这里我将适配器附加到MainActivity中的列表:
newsAdapter = new NewsAdapter( getActivity() , titles , images );
listView.setAdapter(newsAdapter);
每个图像和 Headers 都是ArrayList对象,我想填充我的listview .
这是我的ArrayAdapter:
public class NewsAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<String> titles;
private final ArrayList<String> images;
public NewsAdapter(Context context,ArrayList<String> titles, ArrayList<String> images ) {
super(context, R.layout.drawer_list_item, titles);
this.context = context;
this.titles = titles;
this.images = images;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.news_list_item, parent, false);
TextView title = (TextView) rowView.findViewById(R.id.news_title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.news_thumble);
title.setText(titles.get(position));
new DownloadImageTask(imageView).execute(images.get(position));
return rowView;
}
}
此代码完美运行,listView填充了数据(图像和 Headers ) .
The Question:
是否可以在此实现中附加Listview(添加更多行)? (例如使用newsAdapter.add()方法) .
如果这是可能的,如何实现呢?
1 回答
是的,您可以在自定义适配器中实现
addItem(String title, String image)
方法 . 然后,此方法将传递的值添加到titles
和images
列表中 .更改listadapter的内容后,您必须通过调用该适配器中的
notifyDataSetChanged()
来重新设置列表视图,从而使视图无效 .然后在主活动中调用此方法以向列表中添加更多项目 . (例如
newsAdapter.addItem("some Title", imageString);