2011年5月8日日曜日

ExpandableListViewの長押し

ExpandableListViewでは、アイテムの長押しを setOnLongClickListenerで設定できない。
コンテクストメニューを使って実現する。

こんな感じで設定しておく。
mExpandableListView
    .setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

     @Override
     public void onCreateContextMenu(ContextMenu menu, View v,
       ContextMenuInfo menuInfo) {

      ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
      int type = ExpandableListView
        .getPackedPositionType(info.packedPosition);
      int groupPosition = ExpandableListView
        .getPackedPositionGroup(info.packedPosition);
      int childPosition = ExpandableListView
        .getPackedPositionChild(info.packedPosition);
      // Only create a context menu for child items
      if (type == 1) {

       // Array created earlier when we built the
       // expandable list
       Contact contact = (Contact) mAdapter.getChild(
         groupPosition, childPosition);
       menu.setHeaderTitle(contact.getName());
       menu.add(0, MENU_EDIT, 0, "Edit birthday");
       menu.add(0, MENU_DELETE, 1, "Delete birthday");
      }
     }

    });

メニューが選ばれたらそれを実行。
public boolean onContextItemSelected(MenuItem menuItem) {
  ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem
    .getMenuInfo();
  int groupPos = 0, childPos = 0;
  int type = ExpandableListView
    .getPackedPositionType(info.packedPosition);
  if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
   groupPos = ExpandableListView
     .getPackedPositionGroup(info.packedPosition);
   childPos = ExpandableListView
     .getPackedPositionChild(info.packedPosition);
  }

  Contact contact = (Contact) mAdapter.getChild(groupPos, childPos);
  switch (menuItem.getItemId()) {
  case MENU_EDIT:
   dateDialog(contact, contact.getBirthday());
   return true;
  case MENU_DELETE:
   deleteBirthday(contact);
  default:
   return super.onContextItemSelected(menuItem);
  }
 }

0 件のコメント:

コメントを投稿