views:

9984

answers:

3

I am using a ListView to present the main screen of my application. The main screen is essentially a menu to get into the different sections of my application. Currently I have the ListView contents generatings programmatically in the onCreate method. Here is the code snippet that does this:

String[] mainItems = {
    "Inbox", "Projects", "Contexts", "Next Actions"
}

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    setListAdapter(new ArrayAdapter<String>(
         this, android.R.layout.simple_list_item_1, mainItems));
    registerForContextMenu(getListView());
}

So the menu is essentially just a bunch of nodes with the text contained in the mainItems array. I know that I can create an XML layout (i.e. R.layout.mainMenu_item) that has an ImageView and TextView in it, but I am unsure how to set the ImageView's icon. I have seen that there is a setImageResouce(int resId) method, but the way to use this when generating with an ArrayAdapter is eluding me. Is there a better way to do this?

A: 

From the google docs for ArrayAdapter.

To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

Feet
+6  A: 

What I typically do for a ListView is to implement my own Adapter by extending the handy BaseAdapter class. One of the abstract methods you'll implement will be getView() as the previous poster mentioned. From there you can inflate a layout containing an ImageView, get a reference to it using findViewById, and set the image to whatever drawable you've added into your resources.

public View getView(int position, View convertView, ViewGroup parent) {

    View row = inflater.inflate(R.layout.menu_row, null);

     ImageView icon = (ImageView) row.findViewById(R.id.icon);
     icon.setImageResource(..your drawable's id...);

     return view;
}
Note that you really should look at convertView and only inflate new rows if you truly need them. If convertView is not null, it is some past row you inflated before, up for recycling. Just reset the icon and return the recycled row. Less garbage created, faster execution.
CommonsWare
A: 

No more getView for the ListView in 1.5. Is there a new solution to achieve the above functionality?

getView is a method you override in you implementation of BaseAdapter class and is still there in 1.5 SDK
tdelev
Oh yes, sorry I was not reading carefuly... Thank you!