Android: long click on the child views of a ExpandableListView?

前端 未结 5 708
星月不相逢
星月不相逢 2020-12-02 06:41

ExpandableListView has a setOnChildClickListener method, but lacks of setOnChildLongClickListener method.

When I added setOnL

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 07:32

    I managed to get long clicks working on an ExpandableListView child item, using the following:

    getExpandableListView().setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
            if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
                int groupPosition = ExpandableListView.getPackedPositionGroup(id);
                int childPosition = ExpandableListView.getPackedPositionChild(id);
    
                // You now have everything that you would as if this was an OnChildClickListener() 
                // Add your logic here.
    
                // Return true as we are handling the event.
                return true;
            }
    
            return false;
        }
    });
    

    It took ages to figure out that the id argument in onItemLongClick was the packedPosition argument required by getPackedPosition* methods, certainly not clear from the documentation.

    Note: For this solution to work you need to override the getGroupId and getChildId() methods in your adapter

       @Override
       public long getGroupId(int groupPosition) {
          return groupPosition;
       }
    
       @Override
       public long getChildId(int groupPosition, int childPosition) {
          return childPosition;
       }
    

提交回复
热议问题