Handling list interactions

Now, one common feature of every ListView in Android is that the user should often be able to select a row in the list and expect some sort of added functionality. For instance, maybe you have a list of restaurants, and selecting a specific restaurant within the list brings you to a more detailed description page. This is again where the ListActivity class comes in handy, as one method we can override is the onListItemClick() method. This method takes several parameters, but one of the most important is the position parameter.

The full declaration of the method is as follows:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {    }

And once we have the position index, regardless of whether or not our underlying data is a Cursor or a list of objects, we can use this position index to retrieve the desired row/object. The code for the previous CursorAdapter example would look like the following:

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Cursor c = (Cursor) cAdapter.getItem(position);

        int nameCol = c.getColumnIndex(Phone.DISPLAY_NAME);
        int numCol = c.getColumnIndex(Phone.NUMBER);
        int typeCol = c.getColumnIndex(Phone.TYPE);

        String name = c.getString(nameCol);
        String number = c.getString(numCol);
        int type = c.getInt(typeCol);

        System.out.println("CLICKED ON " + name + " " + number + " " + type);
    }

Similarly, the code for the BaseAdapter example would be as follows:

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        ContactEntry c = contacts.get(position);

        String name = c.getName();
        String number = c.getNumber();
        String type = c.getType();

        System.out.println("CLICKED ON " + name + " " + number + " " + type);
    }

Both are pretty similar and pretty self-explanatory. We simply retrieve the desired row/object using the position index, and then output the desired fields. Oftentimes, the developer might have a separate Activity where they would give the user more details on the object in the row they clicked (that is, the restaurant, the contact, and so on). This may require passing the ID (or some other identifier) of the row/object from the ListActivity to the new details Activity, and this is done through embedding fields into Intent objects – but more on this in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.246.218