问题
I have a listview which i populate using cusome ArrayAdapter , each row in the listview contain image and title .
i followed this tutorial http://www.vogella.com/tutorials/AndroidListView/article.html to create custom arrayadapter and populate my listview using it like the following :
here i attach the adapter to my list in MainActivity:
newsAdapter = new NewsAdapter( getActivity() , titles , images );
listView.setAdapter(newsAdapter);
each of images and titles are ArrayList objects which i want to populate my listview with.
here is my 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;
}
}
this code works perfectly and the listView populated with the data (images and titles).
The Question:
Is it possible to append the Listview (Add more rows) in this implementation ? (e.g using newsAdapter.add() method) .
and if this is possible , how to achieve that ?
回答1:
yeah, you could for example implement an addItem(String title, String image)
method in your custom adapter.
this method then adds the passed values to your titles
and images
list.
after changing the content of the listadapter you have to invalidate the view by calling notifyDataSetChanged()
in that adapter to redraw the listview.
call this method then in your main activity to add more items to the list. (eg newsAdapter.addItem("some Title", imageString);
来源:https://stackoverflow.com/questions/21831437/adding-more-items-to-custom-arrayadapter