Custom Adapter Issue. [closed]
I am trying to build a ListView that has checkBox, Textview and a image, and this should repeat in rows as a scrollable list.
I followed the Android hello-listvi开发者_JS百科ew tutorial but get an error when I customized the xml file and reference it in:
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
I am sure, I need an customized adapter that can place each country name in respective rows, but not able to understand how to do it. Can you please help me out. Thanks a lot.
Here are the high level steps you need to create a custom ListView row with multiple pieces of data.
- Create a class to hold the data that each row needs. In this case that appears to be a boolean, a string, and a drawable or id to a drawable. Let's call this class Foo.
- Create a custom layout xml file for your list row (refrerenced as custom_list_layout below)
Create a custom adapter called FooAdapter which will take a list of Foos in it's constructor.
In the getView() method of your FooAdapter you will inflate your custom view for this row, find all the elements by id, and fill them out with data from your Foo. Something like this:
public class FooAdapter extends ArrayAdapter {
private List<Foo> foos; public FooAdapater(Context ctx, int textViewResourceId, ArrayList<Foo> items) { super(ctx, textViewResourceId, items); this.foos = items; } @Override public View getView(int pos, View view, ViewGroup parent) { final LayoutInflater inflater = parent.getLayoutInflater(); final View entry = inflater.inflate(R.layout.custom_list_layout, null); Foo foo = foos.get(position); TextView tv = (TextView) entry.findViewById(R.id.custom_layout_text_view); tv.setText(foo.getTitle()); // do the same for the checkbox and image return v; }
}
Finally, in your Activity instantiate this adapter instead of the "new ArrayAdapter" passing in your List.
精彩评论