What is the intent of the methods getItem and getItemId in the Android class BaseAdapter?

前端 未结 6 1487
清歌不尽
清歌不尽 2020-11-27 11:47

I\'m curious about the purpose of the methods getItem and getItemId in the class Adapter in the Android SDK.

From the description, it seems that getItem

6条回答
  •  遥遥无期
    2020-11-27 12:08

    getItem or getItemId are few method mainly designed to attached data with items in the list. In case of getItem, you can pass any object that will attach to the item in the list. Normally people return null. getItemId is any unique long value you can attach with the same item in the list. People generally return the position in the list.

    What's the use. Well, as these values are bound to the item in the list, you can extract them when user clicks on the item. These values are accessible through AdapterView methods.

    // template class to create list item objects
    class MyListItem{
        public String name;
        public long dbId;
    
        public MyListItem(String name, long dbId){
            this.name = name;
            this.dbId = dbId;
        }
    }
    
    ///////////////////////////////////////////////////////////
    
    // create ArrayList of MyListItem
    ArrayList myListItems = new ArrayList(10);
    
    // override BaseAdapter methods
    @Override
    public Object getItem(int position) {
        // return actual object 
        // which will be available with item in ListView
        return myListItems.get(position);
    }
    
    @Override
    public long getItemId(int position) {
        // return id of database document object
        return myListItems.get(position).dbId;
    }
    
    ///////////////////////////////////////////////////////////
    
    // on list item click, get name and database document id
    my_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
    
            // extract item data
            MyListItem selectedItem = (MyListItem)parent.getItemAtPosition(position);      
            System.out.println("Your name is : " + selectedItem.name);
    
            // extract database ref id
            long dbId = id;
    
            // or you could also use
            long dbId = parent.getItemIdAtPosition(position);
        }
    });
    

提交回复
热议问题